tania
tania

Reputation: 1086

Splitting a list to sublists containing equal numbers

I'm looking for functional, java 8, solution for a problem of splitting an array into list of sublists 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 managed to come only to the solution for counting these elements:

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

results in a map of count - value, which is not good enough.

would be glad to receive some hints, I guess I do need to map first somehow and then get the entrySet;

Upvotes: 3

Views: 683

Answers (1)

Robin Topper
Robin Topper

Reputation: 2345

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 gets 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())));

Upvotes: 6

Related Questions