com.google.common.collect.Maps.filterKeys()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(185)

本文整理了Java中com.google.common.collect.Maps.filterKeys()方法的一些代码示例,展示了Maps.filterKeys()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Maps.filterKeys()方法的具体详情如下:
包路径:com.google.common.collect.Maps
类名称:Maps
方法名:filterKeys

Maps.filterKeys介绍

[英]Returns a bimap containing the mappings in unfiltered whose keys satisfy a predicate. The returned bimap is a live view of unfiltered; changes to one affect the other.

The resulting bimap's keySet(), entrySet(), and values() views have iterators that don't support remove(), but all other methods are supported by the bimap and its views. When given a key that doesn't satisfy the predicate, the bimap's put(), forcePut() and putAll() methods throw an IllegalArgumentException.

When methods such as removeAll() and clear() are called on the filtered bimap or its views, only mappings that satisfy the filter will be removed from the underlying bimap.

The returned bimap isn't threadsafe or serializable, even if unfiltered is.

Many of the filtered bimap's methods, such as size(), iterate across every key in the underlying bimap and determine which satisfy the filter. When a live view is not needed, it may be faster to copy the filtered bimap and use the copy.

Warning: entryPredicate must be consistent with equals , as documented at Predicate#apply.
[中]返回一个bimap,其中包含键满足谓词的未筛选映射。返回的bimap是未过滤的实时视图;对其中一个的更改会影响另一个。
生成的bimap的keySet()、entrySet()和values()视图具有不支持remove()的迭代器,但bimap及其视图支持所有其他方法。当给定一个不满足谓词的键时,bimap的put()、forcePut()和putAll()方法会抛出一个IllegalArgumentException。
当对过滤后的bimap或其视图调用removeAll()和clear()等方法时,只会从基础bimap中删除满足过滤器的映射。
返回的bimap不是线程安全的或可序列化的,即使是未筛选的。
许多过滤后的bimap方法,例如size(),都会在基础bimap中的每个键上迭代,并确定哪个键满足过滤器的要求。当不需要实时视图时,复制过滤后的bimap并使用副本可能会更快。
警告:entryPredicate必须与equals一致,如Predicate#apply中所述。

代码示例

代码示例来源:origin: google/guava

@Override
Map<K, Collection<V>> createAsMap() {
 return Maps.filterKeys(unfiltered.asMap(), keyPredicate);
}

代码示例来源:origin: google/j2objc

@Override
Map<K, Collection<V>> createAsMap() {
 return Maps.filterKeys(unfiltered.asMap(), keyPredicate);
}

代码示例来源:origin: apache/incubator-druid

@Override
 public List<K> apply(final V input)
 {
  return Lists.newArrayList(Maps.filterKeys(mapCache, new Predicate<K>()
  {
   @Override
   public boolean apply(K key)
   {
    V retVal = mapCache.get(key);
    if (retVal == null) {
     return false;
    }
    return retVal.equals(input);
   }
  }).keySet());
 }
}

代码示例来源:origin: Graylog2/graylog2-server

public Message(final Map<String, Object> fields) {
  this((String) fields.get(FIELD_ID), Maps.filterKeys(fields, not(equalTo(FIELD_ID))));
}

代码示例来源:origin: prestodb/presto

@GET
  @Path("failed")
  public Collection<HeartbeatFailureDetector.Stats> getFailed()
  {
    return Maps.filterKeys(failureDetector.getStats(), in(failureDetector.getFailed())).values();
  }
}

代码示例来源:origin: apache/incubator-druid

private void logIt(String format)
 {
  if (t == null) {
   error(format, description, dataMap);
  } else {
   // Filter out the stack trace from the message, because it should be in the logline already if it's wanted.
   error(
     t,
     format,
     description,
     Maps.filterKeys(dataMap, Predicates.not(Predicates.equalTo("exceptionStackTrace")))
   );
  }
 }
}

代码示例来源:origin: google/guava

@Override
 protected Map<String, String> create(Entry<String, String>[] entries) {
  Map<String, String> map = Maps.newHashMap();
  putEntries(map, entries);
  map.putAll(ENTRIES_TO_FILTER);
  return Maps.filterKeys(map, FILTER_KEYS);
 }
})

代码示例来源:origin: google/guava

@Override
 protected NavigableMap<String, String> create(Entry<String, String>[] entries) {
  NavigableMap<String, String> map = new SafeTreeMap<>();
  putEntries(map, entries);
  map.put("banana", "toast");
  map.put("eggplant", "spam");
  return Maps.filterKeys(map, FILTER_KEYS);
 }
})

代码示例来源:origin: apache/incubator-druid

public Map<String, Object> contents(AlertEvent a)
 {
  return Maps.filterKeys(a.toMap(), new Predicate<String>()
  {
   @Override
   public boolean apply(String k)
   {
    return !"timestamp".equals(k);
   }
  });
 }
}

代码示例来源:origin: google/guava

@Override
 protected BiMap<String, String> create(Entry<String, String>[] entries) {
  BiMap<String, String> map = HashBiMap.create();
  putEntries(map, entries);
  map.putAll(ENTRIES_TO_FILTER);
  return Maps.filterKeys(map, FILTER_KEYS);
 }
})

代码示例来源:origin: google/guava

public void testFilteredKeysIllegalPut() {
 Map<String, Integer> unfiltered = createUnfiltered();
 Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
 filtered.put("a", 1);
 filtered.put("b", 2);
 assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
 try {
  filtered.put("yyy", 3);
  fail();
 } catch (IllegalArgumentException expected) {
 }
}

代码示例来源:origin: google/guava

@Override
 protected SortedMap<String, String> create(Entry<String, String>[] entries) {
  SortedMap<String, String> map = new NonNavigableSortedMap();
  putEntries(map, entries);
  map.putAll(ENTRIES_TO_FILTER);
  return Maps.filterKeys(map, FILTER_KEYS);
 }
})

代码示例来源:origin: google/guava

public void testFilteredKeysIllegalPutAll() {
 Map<String, Integer> unfiltered = createUnfiltered();
 Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
 filtered.put("a", 1);
 filtered.put("b", 2);
 assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
 try {
  filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5));
  fail();
 } catch (IllegalArgumentException expected) {
 }
 assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered);
}

代码示例来源:origin: google/guava

public void testFilteredKeysFilteredReflectsBackingChanges() {
 Map<String, Integer> unfiltered = createUnfiltered();
 Map<String, Integer> filtered = Maps.filterKeys(unfiltered, NOT_LENGTH_3);
 unfiltered.put("two", 2);
 unfiltered.put("three", 3);
 unfiltered.put("four", 4);
 assertEquals(ImmutableMap.of("two", 2, "three", 3, "four", 4), unfiltered);
 assertEquals(ImmutableMap.of("three", 3, "four", 4), filtered);
 unfiltered.remove("three");
 assertEquals(ImmutableMap.of("two", 2, "four", 4), unfiltered);
 assertEquals(ImmutableMap.of("four", 4), filtered);
 unfiltered.clear();
 assertEquals(ImmutableMap.of(), unfiltered);
 assertEquals(ImmutableMap.of(), filtered);
}

代码示例来源:origin: prestodb/presto

private SubPlan buildFragment(PlanNode root, FragmentProperties properties, PlanFragmentId fragmentId)
{
  Set<Symbol> dependencies = SymbolsExtractor.extractOutputSymbols(root);
  List<PlanNodeId> schedulingOrder = scheduleOrder(root);
  boolean equals = properties.getPartitionedSources().equals(ImmutableSet.copyOf(schedulingOrder));
  checkArgument(equals, "Expected scheduling order (%s) to contain an entry for all partitioned sources (%s)", schedulingOrder, properties.getPartitionedSources());
  PlanFragment fragment = new PlanFragment(
      fragmentId,
      root,
      Maps.filterKeys(types.allTypes(), in(dependencies)),
      properties.getPartitioningHandle(),
      schedulingOrder,
      properties.getPartitioningScheme(),
      StageExecutionDescriptor.ungroupedExecution(),
      statsAndCosts.getForSubplan(root));
  return new SubPlan(fragment, properties.getChildren());
}

代码示例来源:origin: ben-manes/caffeine

@Test(dataProvider = "caches")
@CacheSpec(population = { Population.PARTIAL, Population.FULL })
public void invalidateAll_partial(Cache<Integer, Integer> cache, CacheContext context) {
 List<Integer> keys = cache.asMap().keySet().stream()
   .filter(i -> ((i % 2) == 0))
   .collect(Collectors.toList());
 cache.invalidateAll(keys);
 assertThat(cache.estimatedSize(), is(context.initialSize() - keys.size()));
 assertThat(cache, hasRemovalNotifications(context, keys.size(), RemovalCause.EXPLICIT));
 verifyWriter(context, (verifier, writer) -> {
  verifier.deletedAll(Maps.filterKeys(context.original(), Predicates.in(keys)), RemovalCause.EXPLICIT);
 });
}

代码示例来源:origin: prestodb/presto

@BeforeMethod
public void setUp()
{
  scanAssignments = ImmutableMap.<Symbol, ColumnHandle>builder()
      .put(A, new TestingColumnHandle("a"))
      .put(B, new TestingColumnHandle("b"))
      .put(C, new TestingColumnHandle("c"))
      .put(D, new TestingColumnHandle("d"))
      .put(E, new TestingColumnHandle("e"))
      .put(F, new TestingColumnHandle("f"))
      .build();
  Map<Symbol, ColumnHandle> assignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(A, B, C, D, E, F)));
  baseTableScan = new TableScanNode(
      newId(),
      DUAL_TABLE_HANDLE,
      ImmutableList.copyOf(assignments.keySet()),
      assignments);
  expressionNormalizer = new ExpressionIdentityNormalizer();
}

代码示例来源:origin: prestodb/presto

@Override
  protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, TableScanNode tableScanNode, Set<Symbol> referencedOutputs)
  {
    return Optional.of(
        new TableScanNode(
            tableScanNode.getId(),
            tableScanNode.getTable(),
            filteredCopy(tableScanNode.getOutputSymbols(), referencedOutputs::contains),
            filterKeys(tableScanNode.getAssignments(), referencedOutputs::contains),
            tableScanNode.getLayout(),
            tableScanNode.getCurrentConstraint(),
            tableScanNode.getEnforcedConstraint()));
  }
}

代码示例来源:origin: SonarSource/sonarqube

/**
 * Return measures that were added by the step (using {@link #add(Component, Metric, Measure)}).
 * It does not contain the one added in the test by {@link #addRawMeasure(int, String, Measure)}
 */
public SetMultimap<String, Measure> getAddedRawMeasures(Component component) {
 checkAndInitProvidersState();
 ImmutableSetMultimap.Builder<String, Measure> builder = ImmutableSetMultimap.builder();
 for (Map.Entry<InternalKey, Measure> entry : from(filterKeys(rawMeasures, hasComponentRef(component)).entrySet()).filter(isAddedMeasure)) {
  builder.put(entry.getKey().getMetricKey(), entry.getValue());
 }
 return builder.build();
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public SetMultimap<String, Measure> getRawMeasures(Component component) {
 ImmutableSetMultimap.Builder<String, Measure> builder = ImmutableSetMultimap.builder();
 for (Map.Entry<InternalKey, Measure> entry : filterKeys(rawMeasures, hasComponentRef(component)).entrySet()) {
  builder.put(entry.getKey().getMetricKey(), entry.getValue());
 }
 return builder.build();
}

相关文章