List of usage examples for com.google.common.collect ImmutableListMultimap builder
public static <K, V> Builder<K, V> builder()
From source file:org.tensorics.core.tensor.TensorPair.java
/** * Extracts pairs of values, according to the given multimap of position pairs and returns them again as a multimap. * The map will contain the same keys as the input map and as values all the values indexed by the given position * pairs (values of the input map). It is assumed that values exist in the tensors for all given positions. If this * is not the case, then an exception will be thrown. The returned value will be a {@link ListMultimap}, because it * is easily possible that the returned value pairs are the same for different keys. * //w w w.j a v a2s . c om * @param positionPairs a multimap K: pairs of positions for which to retrieve the values * @return a multimap K: pairs of values, extracted from the tensor pair */ public <K> ListMultimap<K, ValuePair<V>> mapValues(Multimap<K, PositionPair> positionPairs) { ImmutableListMultimap.Builder<K, ValuePair<V>> builder = ImmutableListMultimap.builder(); for (Entry<K, Collection<PositionPair>> entry : positionPairs.asMap().entrySet()) { builder.putAll(entry.getKey(), getAll(entry.getValue())); } return builder.build(); }
From source file:co.paralleluniverse.comsat.webactors.servlet.HttpRequestWrapper.java
@Override public final Multimap<String, String> getParameters() { if (params == null) { final ImmutableListMultimap.Builder<String, String> mm = ImmutableListMultimap.builder(); for (final Enumeration<String> ps = request.getParameterNames(); ps.hasMoreElements();) { final String p = ps.nextElement(); final String[] pvs = request.getParameterValues(p); if (pvs != null) { for (final String pv : pvs) mm.put(p, pv);//from w w w.j a va2s . c o m } } this.params = mm.build(); } return params; }
From source file:com.facebook.presto.sql.gen.InCodeGenerator.java
@Override public ByteCodeNode generateExpression(Signature signature, ByteCodeGeneratorContext generatorContext, Type returnType, List<RowExpression> arguments) { ByteCodeNode value = generatorContext.generate(arguments.get(0)); List<RowExpression> values = arguments.subList(1, arguments.size()); ImmutableList.Builder<ByteCodeNode> valuesByteCode = ImmutableList.builder(); for (int i = 1; i < arguments.size(); i++) { ByteCodeNode testNode = generatorContext.generate(arguments.get(i)); valuesByteCode.add(testNode);/*from w ww . j a va2 s .com*/ } Type type = arguments.get(0).getType(); Class<?> javaType = type.getJavaType(); SwitchGenerationCase switchGenerationCase = checkSwitchGenerationCase(type, values); Signature hashCodeSignature = internalOperator(HASH_CODE, BIGINT, ImmutableList.of(type)); MethodHandle hashCodeFunction = generatorContext.getRegistry() .getScalarFunctionImplementation(hashCodeSignature).getMethodHandle(); ImmutableListMultimap.Builder<Integer, ByteCodeNode> hashBucketsBuilder = ImmutableListMultimap.builder(); ImmutableList.Builder<ByteCodeNode> defaultBucket = ImmutableList.builder(); ImmutableSet.Builder<Object> constantValuesBuilder = ImmutableSet.builder(); for (RowExpression testValue : values) { ByteCodeNode testByteCode = generatorContext.generate(testValue); if (testValue instanceof ConstantExpression && ((ConstantExpression) testValue).getValue() != null) { ConstantExpression constant = (ConstantExpression) testValue; Object object = constant.getValue(); switch (switchGenerationCase) { case DIRECT_SWITCH: case SET_CONTAINS: constantValuesBuilder.add(object); break; case HASH_SWITCH: try { int hashCode = Ints.checkedCast((Long) hashCodeFunction.invoke(object)); hashBucketsBuilder.put(hashCode, testByteCode); } catch (Throwable throwable) { throw new IllegalArgumentException( "Error processing IN statement: error calculating hash code for " + object, throwable); } break; default: throw new IllegalArgumentException( "Not supported switch generation case: " + switchGenerationCase); } } else { defaultBucket.add(testByteCode); } } ImmutableListMultimap<Integer, ByteCodeNode> hashBuckets = hashBucketsBuilder.build(); ImmutableSet<Object> constantValues = constantValuesBuilder.build(); LabelNode end = new LabelNode("end"); LabelNode match = new LabelNode("match"); LabelNode noMatch = new LabelNode("noMatch"); LabelNode defaultLabel = new LabelNode("default"); Scope scope = generatorContext.getScope(); ByteCodeNode switchBlock; ByteCodeBlock switchCaseBlocks = new ByteCodeBlock(); LookupSwitch.LookupSwitchBuilder switchBuilder = lookupSwitchBuilder(); switch (switchGenerationCase) { case DIRECT_SWITCH: // A white-list is used to select types eligible for DIRECT_SWITCH. // For these types, it's safe to not use presto HASH_CODE and EQUAL operator. for (Object constantValue : constantValues) { switchBuilder.addCase(Ints.checkedCast((Long) constantValue), match); } switchBuilder.defaultCase(defaultLabel); switchBlock = new ByteCodeBlock().comment("lookupSwitch(<stackValue>))").dup(javaType) .append(new IfStatement() .condition(new ByteCodeBlock().dup(javaType).invokeStatic(InCodeGenerator.class, "isInteger", boolean.class, long.class)) .ifFalse(new ByteCodeBlock().pop(javaType).gotoLabel(defaultLabel))) .longToInt().append(switchBuilder.build()); break; case HASH_SWITCH: for (Map.Entry<Integer, Collection<ByteCodeNode>> bucket : hashBuckets.asMap().entrySet()) { LabelNode label = new LabelNode("inHash" + bucket.getKey()); switchBuilder.addCase(bucket.getKey(), label); Collection<ByteCodeNode> testValues = bucket.getValue(); ByteCodeBlock caseBlock = buildInCase(generatorContext, scope, type, label, match, defaultLabel, testValues, false); switchCaseBlocks.append(caseBlock.setDescription("case " + bucket.getKey())); } switchBuilder.defaultCase(defaultLabel); Binding hashCodeBinding = generatorContext.getCallSiteBinder().bind(hashCodeFunction); switchBlock = new ByteCodeBlock().comment("lookupSwitch(hashCode(<stackValue>))").dup(javaType) .append(invoke(hashCodeBinding, hashCodeSignature)).longToInt().append(switchBuilder.build()) .append(switchCaseBlocks); break; case SET_CONTAINS: Set<?> constantValuesSet = toFastutilHashSet(constantValues, type, registry); Binding constant = generatorContext.getCallSiteBinder().bind(constantValuesSet, constantValuesSet.getClass()); switchBlock = new ByteCodeBlock().comment("inListSet.contains(<stackValue>)") .append(new IfStatement().condition(new ByteCodeBlock().comment("value").dup(javaType) .comment("set").append(loadConstant(constant)) // TODO: use invokeVirtual on the set instead. This requires swapping the two elements in the stack .invokeStatic(FastutilSetHelper.class, "in", boolean.class, javaType.isPrimitive() ? javaType : Object.class, constantValuesSet.getClass())) .ifTrue(jump(match))); break; default: throw new IllegalArgumentException("Not supported switch generation case: " + switchGenerationCase); } ByteCodeBlock defaultCaseBlock = buildInCase(generatorContext, scope, type, defaultLabel, match, noMatch, defaultBucket.build(), true).setDescription("default"); ByteCodeBlock block = new ByteCodeBlock().comment("IN").append(value) .append(ifWasNullPopAndGoto(scope, end, boolean.class, javaType)).append(switchBlock) .append(defaultCaseBlock); ByteCodeBlock matchBlock = new ByteCodeBlock().setDescription("match").visitLabel(match).pop(javaType) .append(generatorContext.wasNull().set(constantFalse())).push(true).gotoLabel(end); block.append(matchBlock); ByteCodeBlock noMatchBlock = new ByteCodeBlock().setDescription("noMatch").visitLabel(noMatch).pop(javaType) .push(false).gotoLabel(end); block.append(noMatchBlock); block.visitLabel(end); return block; }
From source file:org.optaplanner.core.impl.heuristic.selector.SelectorTestUtils.java
public static ValueSelector mockValueSelectorForEntity(Class entityClass, Object entity, String variableName, Object... values) {/* w w w . jav a2 s. c o m*/ return mockValueSelectorForEntity(entityClass, variableName, ImmutableListMultimap.builder().putAll(entity, values).build()); }
From source file:io.prestosql.sql.gen.InCodeGenerator.java
@Override public BytecodeNode generateExpression(Signature signature, BytecodeGeneratorContext generatorContext, Type returnType, List<RowExpression> arguments) { List<RowExpression> values = arguments.subList(1, arguments.size()); // empty IN statements are not allowed by the standard, and not possible here // the implementation assumes this condition is always met checkArgument(values.size() > 0, "values must not be empty"); Type type = arguments.get(0).getType(); Class<?> javaType = type.getJavaType(); SwitchGenerationCase switchGenerationCase = checkSwitchGenerationCase(type, values); Signature hashCodeSignature = generatorContext.getRegistry().resolveOperator(HASH_CODE, ImmutableList.of(type));// www .java 2s . co m MethodHandle hashCodeFunction = generatorContext.getRegistry() .getScalarFunctionImplementation(hashCodeSignature).getMethodHandle(); Signature isIndeterminateSignature = generatorContext.getRegistry().resolveOperator(INDETERMINATE, ImmutableList.of(type)); ScalarFunctionImplementation isIndeterminateFunction = generatorContext.getRegistry() .getScalarFunctionImplementation(isIndeterminateSignature); ImmutableListMultimap.Builder<Integer, BytecodeNode> hashBucketsBuilder = ImmutableListMultimap.builder(); ImmutableList.Builder<BytecodeNode> defaultBucket = ImmutableList.builder(); ImmutableSet.Builder<Object> constantValuesBuilder = ImmutableSet.builder(); for (RowExpression testValue : values) { BytecodeNode testBytecode = generatorContext.generate(testValue); if (isDeterminateConstant(testValue, isIndeterminateFunction.getMethodHandle())) { ConstantExpression constant = (ConstantExpression) testValue; Object object = constant.getValue(); switch (switchGenerationCase) { case DIRECT_SWITCH: case SET_CONTAINS: constantValuesBuilder.add(object); break; case HASH_SWITCH: try { int hashCode = toIntExact(Long.hashCode((Long) hashCodeFunction.invoke(object))); hashBucketsBuilder.put(hashCode, testBytecode); } catch (Throwable throwable) { throw new IllegalArgumentException( "Error processing IN statement: error calculating hash code for " + object, throwable); } break; default: throw new IllegalArgumentException( "Not supported switch generation case: " + switchGenerationCase); } } else { defaultBucket.add(testBytecode); } } ImmutableListMultimap<Integer, BytecodeNode> hashBuckets = hashBucketsBuilder.build(); ImmutableSet<Object> constantValues = constantValuesBuilder.build(); LabelNode end = new LabelNode("end"); LabelNode match = new LabelNode("match"); LabelNode noMatch = new LabelNode("noMatch"); LabelNode defaultLabel = new LabelNode("default"); Scope scope = generatorContext.getScope(); Variable value = scope.createTempVariable(javaType); BytecodeNode switchBlock; Variable expression = scope.createTempVariable(int.class); SwitchBuilder switchBuilder = new SwitchBuilder().expression(expression); switch (switchGenerationCase) { case DIRECT_SWITCH: // A white-list is used to select types eligible for DIRECT_SWITCH. // For these types, it's safe to not use presto HASH_CODE and EQUAL operator. for (Object constantValue : constantValues) { switchBuilder.addCase(toIntExact((Long) constantValue), jump(match)); } switchBuilder.defaultCase(jump(defaultLabel)); switchBlock = new BytecodeBlock().comment("lookupSwitch(<stackValue>))") .append(new IfStatement() .condition(invokeStatic(InCodeGenerator.class, "isInteger", boolean.class, value)) .ifFalse(new BytecodeBlock().gotoLabel(defaultLabel))) .append(expression.set(value.cast(int.class))).append(switchBuilder.build()); break; case HASH_SWITCH: for (Map.Entry<Integer, Collection<BytecodeNode>> bucket : hashBuckets.asMap().entrySet()) { Collection<BytecodeNode> testValues = bucket.getValue(); BytecodeBlock caseBlock = buildInCase(generatorContext, scope, type, match, defaultLabel, value, testValues, false, isIndeterminateSignature, isIndeterminateFunction); switchBuilder.addCase(bucket.getKey(), caseBlock); } switchBuilder.defaultCase(jump(defaultLabel)); Binding hashCodeBinding = generatorContext.getCallSiteBinder().bind(hashCodeFunction); switchBlock = new BytecodeBlock().comment("lookupSwitch(hashCode(<stackValue>))").getVariable(value) .append(invoke(hashCodeBinding, hashCodeSignature)) .invokeStatic(Long.class, "hashCode", int.class, long.class).putVariable(expression) .append(switchBuilder.build()); break; case SET_CONTAINS: Set<?> constantValuesSet = toFastutilHashSet(constantValues, type, registry); Binding constant = generatorContext.getCallSiteBinder().bind(constantValuesSet, constantValuesSet.getClass()); switchBlock = new BytecodeBlock().comment("inListSet.contains(<stackValue>)") .append(new IfStatement().condition(new BytecodeBlock().comment("value").getVariable(value) .comment("set").append(loadConstant(constant)) // TODO: use invokeVirtual on the set instead. This requires swapping the two elements in the stack .invokeStatic(FastutilSetHelper.class, "in", boolean.class, javaType.isPrimitive() ? javaType : Object.class, constantValuesSet.getClass())) .ifTrue(jump(match))); break; default: throw new IllegalArgumentException("Not supported switch generation case: " + switchGenerationCase); } BytecodeBlock defaultCaseBlock = buildInCase(generatorContext, scope, type, match, noMatch, value, defaultBucket.build(), true, isIndeterminateSignature, isIndeterminateFunction) .setDescription("default"); BytecodeBlock block = new BytecodeBlock().comment("IN").append(generatorContext.generate(arguments.get(0))) .append(ifWasNullPopAndGoto(scope, end, boolean.class, javaType)).putVariable(value) .append(switchBlock).visitLabel(defaultLabel).append(defaultCaseBlock); BytecodeBlock matchBlock = new BytecodeBlock().setDescription("match").visitLabel(match) .append(generatorContext.wasNull().set(constantFalse())).push(true).gotoLabel(end); block.append(matchBlock); BytecodeBlock noMatchBlock = new BytecodeBlock().setDescription("noMatch").visitLabel(noMatch).push(false) .gotoLabel(end); block.append(noMatchBlock); block.visitLabel(end); return block; }
From source file:com.google.gerrit.server.git.MergeSuperSet.java
private static ImmutableListMultimap<Branch.NameKey, ChangeData> byBranch(Iterable<ChangeData> changes) throws OrmException { ImmutableListMultimap.Builder<Branch.NameKey, ChangeData> builder = ImmutableListMultimap.builder(); for (ChangeData cd : changes) { builder.put(cd.change().getDest(), cd); }/* w w w . j a v a 2 s . c o m*/ return builder.build(); }
From source file:com.facebook.presto.metadata.NativeMetadata.java
@Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(SchemaTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); ImmutableListMultimap.Builder<SchemaTableName, ColumnMetadata> columns = ImmutableListMultimap.builder(); for (TableColumn tableColumn : dao.listTableColumns(catalogName, prefix.getSchemaName(), prefix.getTableName())) {//from w w w .java 2 s. c o m ColumnMetadata columnMetadata = new ColumnMetadata(tableColumn.getColumnName(), tableColumn.getDataType().toColumnType(), tableColumn.getOrdinalPosition(), false); columns.put(tableColumn.getTable().asSchemaTableName(), columnMetadata); } // This is safe for a list multimap return (Map<SchemaTableName, List<ColumnMetadata>>) (Object) columns.build().asMap(); }
From source file:com.opengamma.strata.measure.fxopt.BlackFxOptionSmileVolatilitiesSpecification.java
@Override public BlackFxOptionSmileVolatilities volatilities(ZonedDateTime valuationDateTime, DoubleArray parameters, ReferenceData refData) {/*from w w w. j a va 2 s . co m*/ ArgChecker.isTrue(parameters.size() == getParameterCount(), Messages .format("Size of parameters must be {}, but found {}", getParameterCount(), parameters.size())); ImmutableListMultimap.Builder<Tenor, Pair<FxOptionVolatilitiesNode, Double>> builder = ImmutableListMultimap .builder(); for (Tenor tenor : nodesByTenor.keys()) { ImmutableList<Pair<FxOptionVolatilitiesNode, Double>> nodesAndQuotes = nodesByTenor.get(tenor).stream() .map(node -> Pair.of(node, parameters.get(nodes.indexOf(node)))).collect(toImmutableList()); builder.putAll(tenor, nodesAndQuotes); } ImmutableListMultimap<Tenor, Pair<FxOptionVolatilitiesNode, Double>> nodesAndQuotesByTenor = builder .build(); List<Tenor> tenors = new ArrayList<>(nodesByTenor.keySet()); Collections.sort(tenors); int nTenors = tenors.size(); int nDeltas = deltas.size(); double[] expiries = new double[nTenors]; double[] atm = new double[nTenors]; double[][] rr = new double[nTenors][nDeltas]; double[][] str = new double[nTenors][nDeltas]; for (int i = 0; i < nTenors; ++i) { parametersForPeriod(valuationDateTime, nodesAndQuotesByTenor.get(tenors.get(i)), i, expiries, atm, rr, str, refData); } InterpolatedStrikeSmileDeltaTermStructure smiles = InterpolatedStrikeSmileDeltaTermStructure.of( DoubleArray.copyOf(expiries), DoubleArray.copyOf(deltas.subList(0, nDeltas)), DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), dayCount, timeInterpolator, timeExtrapolatorLeft, timeExtrapolatorRight, strikeInterpolator, strikeExtrapolatorLeft, strikeExtrapolatorRight); return BlackFxOptionSmileVolatilities.of(name, currencyPair, valuationDateTime, smiles); }
From source file:co.paralleluniverse.comsat.webactors.netty.HttpRequestWrapper.java
static ImmutableListMultimap<String, String> extractHeaders(HttpHeaders headers) { if (headers != null) { final ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (final String n : headers.names()) builder.putAll(n, headers.getAll(n)); return builder.build(); }// w w w .j ava 2 s. c o m return null; }
From source file:org.dishevelled.bio.feature.Gff3Record.java
/** * Parse the GFF3 attributes column into a list multimap of <code><String, String></code> entries. * * @param attributes attributes to parse, must not be null * @return the GFF3 attributes column parsed into a list multimap of <code><String, String></code> entries *//*from w w w .ja va 2s .c o m*/ static ListMultimap<String, String> parseAttributes(final String attributes) { checkNotNull(attributes); ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder(); for (String token : attributes.split(";")) { String[] entry = token.split("="); builder.put(entry[0], entry[1]); } return builder.build(); }