java.util.stream.Collectors.counting()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(8.9k)|赞(0)|评价(0)|浏览(335)

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

Collectors.counting介绍

暂无

代码示例

代码示例来源:origin: stackoverflow.com

import java.util.*;
import java.util.stream.*;

class Test {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();

    list.add("Hello");
    list.add("Hello");
    list.add("World");

    Map<String, Long> counted = list.stream()
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(counted);
  }
}

代码示例来源:origin: AsyncHttpClient/async-http-client

@Override
public Map<String, Long> getIdleChannelCountPerHost() {
 return partitions
     .values()
     .stream()
     .flatMap(ConcurrentLinkedDeque::stream)
     .map(idle -> idle.getChannel().remoteAddress())
     .filter(a -> a.getClass() == InetSocketAddress.class)
     .map(a -> (InetSocketAddress) a)
     .map(InetSocketAddress::getHostName)
     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public static Map<String, Long> countWords(Stream<String> words) {
  return words.collect(groupingBy(word -> word, counting()));
}

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

private static void ensureNoDuplicateName(Set<CoreExtension> coreExtensions) {
 Map<String, Long> nameCounts = coreExtensions.stream()
  .map(CoreExtension::getName)
  .collect(Collectors.groupingBy(t -> t, Collectors.counting()));
 Set<String> duplicatedNames = nameCounts.entrySet().stream()
  .filter(t -> t.getValue() > 1)
  .map(Map.Entry::getKey)
  .collect(MoreCollectors.toSet());
 checkState(duplicatedNames.isEmpty(),
  "Multiple core extensions declare the following names: %s",
  duplicatedNames.stream().sorted().collect(Collectors.joining(", ")));
}

代码示例来源:origin: AsyncHttpClient/async-http-client

public ClientStats getClientStats() {
 Map<String, Long> totalConnectionsPerHost = openChannels.stream().map(Channel::remoteAddress).filter(a -> a.getClass() == InetSocketAddress.class)
     .map(a -> (InetSocketAddress) a).map(InetSocketAddress::getHostName).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
 Map<String, Long> idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost();
 Map<String, HostStats> statsPerHost = totalConnectionsPerHost.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> {
  final long totalConnectionCount = entry.getValue();
  final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L);
  final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
  return new HostStats(activeConnectionCount, idleConnectionCount);
 }));
 return new ClientStats(statsPerHost);
}

代码示例来源:origin: spotify/apollo

private void sanityCheck(List<Route<AsyncHandler<Response<ByteString>>>> routes) {
 Map<String, Long> methodUriCounts = routes.stream()
   .collect(Collectors.groupingBy(Versions::methodUri, counting()));
 Set<String> overlappingMethodUris =
   methodUriCounts.entrySet().stream()
     .filter(entry -> entry.getValue() > 1)
     .map(Map.Entry::getKey)
     .collect(toSet());
 if (!overlappingMethodUris.isEmpty()) {
  throw new IllegalArgumentException(
    "versioned routes overlap for the following method/uris: " + overlappingMethodUris);
 }
}

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public void countWords(InputStream stream) {
  try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
    Map<String, Long> counts = reader
                  .lines()
                  .flatMap(space::splitAsStream)
                  .map(String::trim)
                  .filter(word -> !word.isEmpty())
                  .collect(groupingBy(word -> word, counting()));
    counts.forEach((word, count) -> System.out.println(word + " -> " + count));
  } catch (IOException e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) {
  return albums.collect(groupingBy(album -> album.getMainMusician(),
                   counting()));
}
  // END NUMBER_OF_ALBUMS

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

@VisibleForTesting
static String[] getFrequentLocations(final Stream<String> locations)
{
 final Map<String, Long> locationCountMap = locations.collect(
   Collectors.groupingBy(location -> location, Collectors.counting())
 );
 final Comparator<Map.Entry<String, Long>> valueComparator =
   Map.Entry.comparingByValue(Comparator.reverseOrder());
 final Comparator<Map.Entry<String, Long>> keyComparator =
   Map.Entry.comparingByKey();
 return locationCountMap
   .entrySet().stream()
   .sorted(valueComparator.thenComparing(keyComparator))
   .limit(3)
   .map(Map.Entry::getKey)
   .toArray(String[]::new);
}

代码示例来源:origin: shekhargulati/strman-java

/**
 * Counts the number of occurrences of each character in the string
 *
 * @param input The input string
 * @return A map containing the number of occurrences of each character in the string
 */
public static Map<Character, Long> charsCount(String input) {
  if (isNullOrEmpty(input)) {
    return Collections.emptyMap();
  }
  return input.chars().mapToObj(c -> (char) c).collect(groupingBy(identity(), counting()));
}

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

private boolean isInliningCandidate(Expression expression, ProjectNode node)
{
  // TryExpressions should not be pushed down. However they are now being handled as lambda
  // passed to a FunctionCall now and should not affect predicate push down. So we want to make
  // sure the conjuncts are not TryExpressions.
  verify(AstUtils.preOrder(expression).noneMatch(TryExpression.class::isInstance));
  // candidate symbols for inlining are
  //   1. references to simple constants
  //   2. references to complex expressions that appear only once
  // which come from the node, as opposed to an enclosing scope.
  Set<Symbol> childOutputSet = ImmutableSet.copyOf(node.getOutputSymbols());
  Map<Symbol, Long> dependencies = SymbolsExtractor.extractAll(expression).stream()
      .filter(childOutputSet::contains)
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
  return dependencies.entrySet().stream()
      .allMatch(entry -> entry.getValue() == 1 || node.getAssignments().get(entry.getKey()) instanceof Literal);
}

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

private void classifyFilmsCounting() {
  ExampleUtil.log("classifyFilmsCounting");
  Map<String, Long> map = films.stream()
    .collect(
      Collectors.groupingBy(
        // Apply this classifier
        Film.RATING,
        // Then apply this down-stream collector
        Collectors.counting()
        )
    );
  System.out.println(map);
}

代码示例来源:origin: google/error-prone

@Override
 public Description matchMethodInvocation(
   MethodInvocationTree methodInvocationTree, VisitorState visitorState) {

  if (methodInvocationTree.getArguments().stream()
    .filter(arg -> UNARY_OPERATORS.contains(arg.getKind()))
    .map(arg -> ASTHelpers.getSymbol(((UnaryTree) arg).getExpression()))
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    .entrySet()
    .stream()
    .anyMatch(e -> e.getValue() > 1)) {
   return describeMatch(methodInvocationTree);
  }
  return Description.NO_MATCH;
 }
}

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

protected void testAutoLoadable() {
  Long c = matchingProviders().collect(counting());
  switch (c.intValue()) {
    case 0:
      fail("Expected provider '" + provider.getName() + "' is not found");
      break;
    case 1:
      break;
    default:
      fail("Expected provider '" + provider.getName() + "' is found more then once: " + c);
      break;
  }
}

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

.flatMap(expression -> SymbolsExtractor.extractAll(expression).stream())
.filter(childOutputSet::contains)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

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

@Test
public void testUnusedBinding() {
  assertThatThrownBy(() -> h.createQuery("select * from something")
    .bind("id", 1)
    .collectRows(Collectors.counting())
  ).isInstanceOf(UnableToCreateStatementException.class);
}

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

@Test
// TODO it would be nice if this failed in the future
public void testFarAwayPositional() {
  assertThatCode(() -> h.createQuery("select * from something where id = ?")
    .bind(0, 1)
    .bind(2, "jack")
    .collectRows(Collectors.counting())
  ).doesNotThrowAnyException();
}

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

@Test
// TODO it would be nice if this failed in the future
public void testUsedAndUnusedNamed() {
  assertThatCode(() -> h.createQuery("select * from something where id = :id")
    .bind("id", 1)
    .bind("name", "jack")
    .collectRows(Collectors.counting())
  ).doesNotThrowAnyException();
}

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

@Test
public void testPermittedUnusedBinding() {
  assertThatCode(() -> h.configure(SqlStatements.class, s -> s.setUnusedBindingAllowed(true))
    .createQuery("select * from something")
    .bind("id", 1)
    .collectRows(Collectors.counting())).doesNotThrowAnyException();
}

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

@Test
public void testPermittedUsedAndUnusedBinding() {
  assertThatCode(() -> h.configure(SqlStatements.class, s -> s.setUnusedBindingAllowed(true))
    .createQuery("select * from something where id = :id")
    .bind("id", 1)
    .bind("name", "jack")
    .collectRows(Collectors.counting())).doesNotThrowAnyException();
}

相关文章