Splitting a list into sublists containing the same numbers

I'm looking for a functional java 8 solution to solve the problem of splitting an array into a list of subscriptions containing equal elements;

i.e:.

ArrayList.asList(1,2,2,3,4,4,4) -->  List([1],[2,2],[3], [4,4,4])

      

So far I have only managed to come up with a solution for counting these items:

Map<Integer,Integer> count = lst.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));

      

results in displaying the count value, which is not enough.

would be glad to get some hints, i think i need to somehow display the map first and then get the entrySet;

+3


source to share


1 answer


List<List<Integer>> list = Arrays.asList(1,2,2,3,4,4,4).stream()
    // grouping gets you a Map<Integer,List<Integer>>
    .collect(Collectors.groupingBy(s -> s)) 
    // take the values of this map and create of stream of these List<Integer>s
    .values().stream()   
    // collect them into a List
    .collect(Collectors.toList());   

      

Printing the result gives you the requested list of lists:

System.out.println(list);

      

[ 1 , [2, 2], [3], [4, 4, 4]]




EDIT: credits to Alexis C. for this alternative:

Arrays.asList(1,2,2,3,4,4,4).stream()
   .collect(collectingAndThen(groupingBy(s -> s), m -> new ArrayList<>(m.values())));

      

+5


source







All Articles