Map<Integer, Long> result = Stream.of("first", "second", "third", "fourth", "fifth") .collect(Collectors.groupingBy(s -> s.startsWith("f") ? 0 : s.startsWith("s") ? 1 : 2, Collectors.counting()));