Java Code Examples for com.google.common.collect.Multimap#asMap()

The following examples show how to use com.google.common.collect.Multimap#asMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BooksDataManager.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Loads test data as grouping data from a multimap.
 * 
 * @param data
 *            list of multimap entries of field name to values
 */
public void loadTestData(final List<Map.Entry<Multimap<String,String>,UID>> data) {
    try {
        GroupingAccumuloWriter writer = new GroupingAccumuloWriter(this.datatype, this.accumuloConn, this.cfgData.getDateField(), this.fieldIndex,
                        this.cfgData);
        writer.addData(data);
        Set<RawData> testData = new HashSet<>();
        for (Map.Entry<Multimap<String,String>,UID> entry : data) {
            Multimap<String,String> mm = entry.getKey();
            Map<String,Collection<String>> val = mm.asMap();
            RawData rawEntry = new BooksRawData(this.datatype, this.getHeaders(), this.metadata, val);
            testData.add(rawEntry);
        }
        this.rawData.put(this.datatype, testData);
    } catch (MutationsRejectedException | TableNotFoundException me) {
        throw new AssertionError(me);
    }
}
 
Example 2
Source File: ServiceContext.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@JsonCreator
public ServiceContext(@JsonProperty("service") BaragonService service,
                      @JsonProperty("upstreams") Collection<UpstreamInfo> upstreams,
                      @JsonProperty("timestamp") Long timestamp,
                      @JsonProperty("present") boolean present) {
  this.service = service;
  this.timestamp = timestamp;
  this.upstreams = MoreObjects.firstNonNull(upstreams, Collections.<UpstreamInfo>emptyList());
  this.present = present;
  this.rootPath = service.getServiceBasePath().equals("/");

  if (!this.upstreams.isEmpty()) {
    final Multimap<String, UpstreamInfo> upstreamGroupsMultimap = ArrayListMultimap.create();
    for (UpstreamInfo upstream : this.upstreams) {
      upstreamGroupsMultimap.put(upstream.getGroup(), upstream);
    }
    this.upstreamGroups = upstreamGroupsMultimap.asMap();
  } else {
    this.upstreamGroups = Collections.emptyMap();
  }
}
 
Example 3
Source File: AssignmentQuantityAllocator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Map<EStructuralFeature, Collection<ISyntaxConstraint>> groupByFeature() {
	Multimap<EStructuralFeature, ISyntaxConstraint> map = HashMultimap.create();
	for (ISyntaxConstraint e : assignmentQuants.keySet())
		map.put(e.getAssignmentFeature(delegate.eClass()), e);
	return map.asMap();
}
 
Example 4
Source File: MatchHeaders.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Map<String,String> multimapToCommaSeparatedMap(Multimap<String, String> multimap) {
  Map<String, Collection<String>> mapOfCollections = multimap.asMap();
  HashMap<String, String> map = new HashMap<>();
  for (Map.Entry<String, Collection<String>> entry : mapOfCollections.entrySet()) {
    map.put(entry.getKey(), String.join(",", entry.getValue()));
  }
  return map;
}
 
Example 5
Source File: TypePlanTransformers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns a list of {@link BrooklynTypePlanTransformer} instances for this {@link ManagementContext}
 * which may be able to handle the given plan; the list is sorted with highest-score transformer first */
@Beta
public static List<BrooklynTypePlanTransformer> forType(ManagementContext mgmt, RegisteredType type, RegisteredTypeLoadingContext constraint) {
    Multimap<Double,BrooklynTypePlanTransformer> byScoreMulti = ArrayListMultimap.create(); 
    Collection<BrooklynTypePlanTransformer> transformers = all(mgmt);
    for (BrooklynTypePlanTransformer transformer : transformers) {
        double score = transformer.scoreForType(type, constraint);
        if (score>0) byScoreMulti.put(score, transformer);
    }
    Map<Double, Collection<BrooklynTypePlanTransformer>> tree = new TreeMap<Double, Collection<BrooklynTypePlanTransformer>>(byScoreMulti.asMap());
    List<Collection<BrooklynTypePlanTransformer>> highestFirst = new ArrayList<Collection<BrooklynTypePlanTransformer>>(tree.values());
    Collections.reverse(highestFirst);
    return ImmutableList.copyOf(Iterables.concat(highestFirst));
}
 
Example 6
Source File: AbstractPlayerGamesTest.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
public Map<Integer, Collection<String>> getRooms() {
    Multimap<Integer, String> result = TreeMultimap.create();

    for (PlayerGame playerGame : playerGames) {
        int index = fields.indexOf(playerGame.getField());
        String name = playerGame.getPlayer().getId();

        result.get(index).add(name);
    }
    return result.asMap();
}
 
Example 7
Source File: AbstractPlayerGamesTest.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
public Map<String, Collection<List<String>>> getRoomNames() {
    Multimap<String, List<String>> result = HashMultimap.create();

    playerGames.rooms().forEach(
            (key, value) -> result.get(key).add(players(value)));

    return result.asMap();
}
 
Example 8
Source File: DistributedLabelResourceStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean releaseToDevicePool(Multimap<DeviceId, LabelResource> release) {
    Map<DeviceId, Collection<LabelResource>> maps = release.asMap();
    Set<DeviceId> deviceIdSet = maps.keySet();
    LabelResourceRequest request = null;
    for (Iterator<DeviceId> it = deviceIdSet.iterator(); it.hasNext();) {
        DeviceId deviceId = it.next();
        Device device = deviceService.getDevice(deviceId);
        if (device == null) {
            continue;
        }
        ImmutableSet<LabelResource> collection = ImmutableSet.copyOf(maps
                .get(deviceId));
        request = new LabelResourceRequest(deviceId,
                                           LabelResourceRequest.Type.RELEASE,
                                           0, collection);
        NodeId master = mastershipService.getMasterFor(deviceId);

        if (master == null) {
            log.warn("Failed to releaseToDevicePool: No master for {}", deviceId);
            return false;
        }

        if (master.equals(clusterService.getLocalNode().id())) {
            return internalRelease(request);
        }

        log.trace("Forwarding request to {}, which is the primary (master) for device {}",
                  master, deviceId);

        return complete(clusterCommunicator
                .sendAndReceive(request,
                                LabelResourceMessageSubjects.LABEL_POOL_RELEASE,
                                SERIALIZER::encode, SERIALIZER::decode,
                                master));
    }
    return false;
}
 
Example 9
Source File: CejugErrorMap.java    From hurraa with GNU General Public License v2.0 5 votes vote down vote up
public CejugErrorMap(List<Message> messages) {
	Multimap<String, String> out = ArrayListMultimap.create();
	for (Message message : messages) {
		out.put(message.getCategory(), message.getMessage());
	}
	this.delegate = out.asMap();
	this.messages = messages;
	
}
 
Example 10
Source File: NodeOptions.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Map<WebDriverInfo, Collection<SessionFactory>> discoverDrivers(
  int maxSessions,
  Function<WebDriverInfo, Collection<SessionFactory>> factoryFactory) {

  if (!config.getBool("node", "detect-drivers").orElse(false)) {
    return ImmutableMap.of();
  }

  // We don't expect duplicates, but they're fine
  List<WebDriverInfo> infos =
    StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)
      .filter(WebDriverInfo::isAvailable)
      .sorted(Comparator.comparing(info -> info.getDisplayName().toLowerCase()))
      .collect(Collectors.toList());

  // Same
  List<DriverService.Builder<?, ?>> builders = new ArrayList<>();
  ServiceLoader.load(DriverService.Builder.class).forEach(builders::add);

  Multimap<WebDriverInfo, SessionFactory> toReturn = HashMultimap.create();
  infos.forEach(info -> {
    Capabilities caps = info.getCanonicalCapabilities();
    builders.stream()
      .filter(builder -> builder.score(caps) > 0)
      .forEach(builder -> {
        for (int i = 0; i < Math.min(info.getMaximumSimultaneousSessions(), maxSessions); i++) {
          toReturn.putAll(info, factoryFactory.apply(info));
        }
      });
  });

  return toReturn.asMap();
}
 
Example 11
Source File: CaseInsensitiveMultiMap.java    From ribbon with Apache License 2.0 5 votes vote down vote up
Map<String, Collection<String>> asMap() {
    Multimap<String, String> result = ArrayListMultimap.create();
    Collection<Entry<String, String>> all = map.values();
    for (Entry<String, String> entry: all) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result.asMap();
}
 
Example 12
Source File: Indexer.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
/**
 * groups a list of ids by shard
 * (consider moving this to a BaseSharder class)
 */
private Map<Integer, Collection<String>> shardByValue(List<String> idsToDelete) {
    Multimap<Integer, String> map = Multimaps.index(idsToDelete, new Function<String, Integer>() {
        @Override
        public Integer apply(@Nullable String id) {
            try {
                return sharder.getShard(id);
            } catch (SharderException e) {
                throw new RuntimeException("error calculating hash", e);
            }
        }
    });
    return map.asMap();
}
 
Example 13
Source File: ThirdEyeUtils.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
public static String convertMultiMapToJson(Multimap<String, String> multimap)
    throws JsonProcessingException {
  Map<String, Collection<String>> map = multimap.asMap();
  return OBJECT_MAPPER.writeValueAsString(map);
}
 
Example 14
Source File: HadoopHashMapSelfTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
private void check(HadoopHashMultimap m, Multimap<Integer, Integer> mm, HadoopTaskContext taskCtx) throws Exception {
    final HadoopTaskInput in = m.input(taskCtx);

    Map<Integer, Collection<Integer>> mmm = mm.asMap();

    int keys = 0;

    while (in.next()) {
        keys++;

        IntWritable k = (IntWritable)in.key();

        assertNotNull(k);

        ArrayList<Integer> vs = new ArrayList<>();

        Iterator<?> it = in.values();

        while (it.hasNext())
            vs.add(((IntWritable) it.next()).get());

        Collection<Integer> exp = mmm.get(k.get());

        assertEquals(sorted(exp), sorted(vs));
    }

    X.println("keys: " + keys + " cap: " + m.capacity());

    assertEquals(mmm.size(), keys);

    assertEquals(m.keys(), keys);

    in.close();
}