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); } }
@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())); }
public static Map<String, Long> countWords(Stream<String> words) { return words.collect(groupingBy(word -> word, counting())); }
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(", "))); }
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); }
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); } }
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(); } }
public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) { return albums.collect(groupingBy(album -> album.getMainMusician(), counting())); } // END NUMBER_OF_ALBUMS
@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); }
/** * 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())); }
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); }
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); }
@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; } }
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; } }
.flatMap(expression -> SymbolsExtractor.extractAll(expression).stream()) .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
@Test public void testUnusedBinding() { assertThatThrownBy(() -> h.createQuery("select * from something") .bind("id", 1) .collectRows(Collectors.counting()) ).isInstanceOf(UnableToCreateStatementException.class); }
@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(); }
@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(); }
@Test public void testPermittedUnusedBinding() { assertThatCode(() -> h.configure(SqlStatements.class, s -> s.setUnusedBindingAllowed(true)) .createQuery("select * from something") .bind("id", 1) .collectRows(Collectors.counting())).doesNotThrowAnyException(); }
@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(); }