java.util.Collection类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(7.9k)|赞(0)|评价(0)|浏览(124)

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

Collection介绍

[英]Collection is the root of the collection hierarchy. It defines operations on data collections and the behavior that they will have in all implementations of Collections. All direct or indirect implementations of Collection should implement at least two constructors. One with no parameters which creates an empty collection and one with a parameter of type Collection. This second constructor can be used to create a collection of different type as the initial collection but with the same elements. Implementations of Collectioncannot be forced to implement these two constructors but at least all implementations under java.util do. Methods that change the content of a collection throw an UnsupportedOperationException if the underlying collection does not support that operation, though it's not mandatory to throw such an Exceptionin cases where the requested operation would not change the collection. In these cases it's up to the implementation whether it throws an UnsupportedOperationException or not. Methods marked with (optional) can throw an UnsupportedOperationException if the underlying collection doesn't support that method.
[中]集合是集合层次结构的根。它定义了对数据集合的操作以及它们在集合的所有实现中的行为。集合的所有直接或间接实现应至少实现两个构造函数。一个没有创建空集合的参数,另一个具有collection类型的参数。第二个构造函数可用于创建与初始集合不同类型但具有相同元素的集合。Collections的实现不能强制实现这两个构造函数,但至少要实现java下的所有实现。我知道。如果基础集合不支持该操作,则更改集合内容的方法会引发UnsupportedOperationException,但如果请求的操作不会更改集合,则不强制引发此类异常。在这些情况下,是否抛出UnsupportedOperationException取决于实现。如果基础集合不支持(可选)标记的方法,则该方法可以引发UnsupportedOperationException。

代码示例

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

private ClusterException(Collection<? extends Throwable> exceptions) {
 super(
   exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.",
   exceptions.iterator().next());
 ArrayList<Throwable> temp = new ArrayList<>();
 temp.addAll(exceptions);
 this.exceptions = Collections.unmodifiableCollection(temp);
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void onNext(T t) {
  synchronized (this) {
    U b = buffer;
    if (b != null) {
      b.add(t);
    }
  }
}

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

@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClear() {
 collection.clear();
 assertTrue("After clear(), a collection should be empty.", collection.isEmpty());
 assertEquals(0, collection.size());
 assertFalse(collection.iterator().hasNext());
}

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

/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
 this.map = map;
 totalSize = 0;
 for (Collection<V> values : map.values()) {
  checkArgument(!values.isEmpty());
  totalSize += values.size();
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public Collection<List<String>> values() {
  return this.headers.getHeaderNames().stream()
      .map(this.headers::get)
      .collect(Collectors.toList());
}

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

public List<Symbol> getOriginalDistinctAggregateArgs()
{
  return aggregations.values().stream()
      .filter(aggregation -> aggregation.getMask().isPresent())
      .map(Aggregation::getCall)
      .flatMap(function -> function.getArguments().stream())
      .distinct()
      .map(Symbol::from)
      .collect(Collectors.toList());
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public Set<String> keySet() {
  return this.headers.getHeaderNames().stream()
      .map(HttpString::toString)
      .collect(Collectors.toSet());
}

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

public static boolean dependsOn(WindowNode parent, WindowNode child)
  {
    return parent.getPartitionBy().stream().anyMatch(child.getCreatedSymbols()::contains)
        || (parent.getOrderingScheme().isPresent() && parent.getOrderingScheme().get().getOrderBy().stream().anyMatch(child.getCreatedSymbols()::contains))
        || parent.getWindowFunctions().values().stream()
        .map(WindowNode.Function::getFunctionCall)
        .map(SymbolsExtractor::extractUnique)
        .flatMap(Collection::stream)
        .anyMatch(child.getCreatedSymbols()::contains);
  }
}

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

private void assertCollectionSize(Collection<?> collection, int size) {
  assertEquals(size, collection.size());
  if (size > 0) {
   assertFalse(collection.isEmpty());
  } else {
   assertTrue(collection.isEmpty());
  }
  assertEquals(size, Iterables.size(collection));
  assertEquals(size, Iterators.size(collection.iterator()));
 }
}

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

public void testPermutationSetEmpty() {
 Collection<List<Integer>> permutationSet =
   Collections2.permutations(Collections.<Integer>emptyList());
 assertEquals(1, permutationSet.size());
 assertTrue(permutationSet.contains(Collections.<Integer>emptyList()));
 Iterator<List<Integer>> permutations = permutationSet.iterator();
 assertNextPermutation(Collections.<Integer>emptyList(), permutations);
 assertNoMorePermutations(permutations);
}

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

@Nullable
MonitorEntry getRunningTaskMonitorEntry(String subTaskSpecId)
{
 return runningTasks.values()
           .stream()
           .filter(monitorEntry -> monitorEntry.spec.getId().equals(subTaskSpecId))
           .findFirst()
           .orElse(null);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected void applyCookies() {
  getCookies().values().stream().flatMap(Collection::stream)
      .map(cookie -> new DefaultCookie(cookie.getName(), cookie.getValue()))
      .forEach(this.request::addCookie);
}

代码示例来源:origin: apache/flink

private static int getNumberOfSlotsPerTaskManager(final String host, final int port) throws Exception {
  final TaskManagersInfo taskManagersInfo = restClient.sendRequest(
    host,
    port,
    TaskManagersHeaders.getInstance()).get();
  return taskManagersInfo.getTaskManagerInfos()
    .stream()
    .map(TaskManagerInfo::getNumberSlots)
    .findFirst()
    .orElse(0);
}

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

private static boolean noFilters(AggregationNode aggregation)
{
  return aggregation.getAggregations()
      .values().stream()
      .map(Aggregation::getCall)
      .noneMatch(call -> call.getFilter().isPresent());
}

代码示例来源:origin: spring-projects/spring-framework

private void applyCookiesIfNecessary() {
  if (this.headers.get(HttpHeaders.COOKIE) == null) {
    this.cookies.values().stream().flatMap(Collection::stream)
        .forEach(cookie -> this.headers.add(HttpHeaders.COOKIE, cookie.toString()));
  }
}

代码示例来源:origin: neo4j/neo4j

public void forEach( BiConsumer<String,URI> consumer )
{
  entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
      .forEach( ( key, list ) -> list.stream()
          .max( Comparator.comparing( e -> e.precedence ) )
          .ifPresent( e -> consumer.accept( key, e.uri ) ) );
}

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

@CollectionSize.Require(absent = CollectionSize.ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testEquals_containingNull() {
 Collection<E> elements = getSampleElements(getNumElements() - 1);
 elements.add(null);
 collection = getSubjectGenerator().create(elements.toArray());
 assertTrue(
   "A Set should equal any other Set containing the same elements,"
     + " even if some elements are null.",
   getSet().equals(MinimalSet.from(elements)));
}

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

@CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
 try {
  Iterator<E> iterator = collection.iterator();
  assertTrue(collection.add(e3()));
  iterator.next();
  fail("Expected ConcurrentModificationException");
 } catch (ConcurrentModificationException expected) {
  // success
 }
}

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

public void testUnhashableMixedValues() {
 SampleElements<UnhashableObject> unhashables = new Unhashables();
 Multimap<Integer, Object> multimap =
   ImmutableMultimap.<Integer, Object>of(
     0, unhashables.e0(), 2, "hey you", 0, unhashables.e1());
 assertEquals(2, multimap.get(0).size());
 assertTrue(multimap.get(0).contains(unhashables.e0()));
 assertTrue(multimap.get(0).contains(unhashables.e1()));
 assertTrue(multimap.get(2).contains("hey you"));
}

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

/** An implementation of {@link Multiset#addAll}. */
static <E> boolean addAllImpl(Multiset<E> self, Collection<? extends E> elements) {
 checkNotNull(self);
 checkNotNull(elements);
 if (elements instanceof Multiset) {
  return addAllImpl(self, cast(elements));
 } else if (elements.isEmpty()) {
  return false;
 } else {
  return Iterators.addAll(self, elements.iterator());
 }
}

相关文章