The number of Java instances of each element in an integer array

I wrote the following snippet to count the number of occurrences of each element. Can this be achieved much shorter?

int[] arr = {1, 6, 2, 8, 5, 4, 7, 7, 5, 7};
Arrays.stream(arr)
        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
        .stream()
        .collect(Collectors.groupingBy(s -> s))
        .forEach((k, v) -> System.out.println(k+" "+v.size()));

Also, I would like to display only those elements that occur more than once. Therefore, I tried to change as shown below, which led to an error.

.forEach((k, v) -> if(v.size() > 1) System.out.println(k+" "+v.size()));

What is the right way to do this?

+4
source share
4 answers

For the last question you need to change

.forEach((k, v) -> if(v.size() > 1) System.out.println(k+" "+v.size()));

to

.forEach((k, v) -> {if(v.size() > 1) System.out.println(k+" "+v.size());});

In the first part, it is not clear why you need the first collect, and then the second conveyor Stream. If the goal was to convert IntStreamto Stream<Integer>, use boxed():

Arrays.stream(arr)
      .boxed()
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

, , :

Map<Integer,Integer> occurrences = 
    Arrays.stream(arr)
          .boxed()
          .collect(Collectors.groupingBy(s -> s, Collectors.counting()));
+8

, Eclipse Collections Bag, :

Bags.mutable.with(1, 6, 2, 8, 5, 4, 7, 7, 5, 7)
    .selectByOccurrences(count -> count > 1)
    .forEachWithOccurrences((k, count) -> System.out.println(k+" "+count));

int [] arr int, IntBag. : 9/9/16: selectByOccurrences Bags EC 8.0. int collect(i -> i):

IntBags.mutable.with(arr)
    .selectByOccurrences(count -> count > 1)
    .forEachWithOccurrences((k, count) -> System.out.println(k+" "+count));

: Eclipse.

+3

.

// Solution 1 [Improved from Eran solution & suggestion]
int[] arr = {1, 6, 2, 8, 5, 4, 7, 7, 5, 7};
Map<Integer, Long> counts = Arrays.stream(arr)
    .boxed()
    .collect(collectingAndThen(groupingBy(n -> n, counting()),
        map -> map.entrySet().stream()
            .filter(n -> n.getValue() > 1)
            .collect(toMap(Entry::getKey, Entry::getValue))
));
System.out.println(counts.toString());

// Solution 2 [Improved from Dici suggestion]
int[] arr = {1, 6, 2, 8, 5, 4, 7, 7, 5, 7};
Map<Object, Long> counts = Arrays.stream(arr)
    .collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
    .stream()
    .collect(groupingBy(Function.identity(), counting()));
counts.values().removeIf(count -> count < 2);
System.out.println(counts.toString());  
0

:

 List<Integer> list = ImmutableList.of(1, 2, 3, 4, 5, 6, 3, 4, 5);
 Map<Integer, Integer> result = list.stream().distinct().collect(Collectors.toMap(Function.identity(), token -> Collections.frequency(list, token)));
0

Source: https://habr.com/ru/post/1651210/


All Articles