3

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;

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
tania
  • 1,086
  • 2
  • 12
  • 31
  • 3
    Possible duplicate of [Group sequences of values](http://stackoverflow.com/questions/35234128/group-sequences-of-values). Particularly [Stuart Mark's answer](http://stackoverflow.com/a/35247952/4105457). – Flown May 01 '17 at 11:49

1 Answers1

6
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())));
Community
  • 1
  • 1
Robin Topper
  • 2,295
  • 1
  • 17
  • 25
  • If you expect that, my answer indeed doesn't work. But with the question as it is, is seems to be ok. – Robin Topper May 01 '17 at 11:57
  • yes, question was group all ints in lists based on their equality; the answer is perfect, highly appreciated! – tania May 01 '17 at 14:18
  • 3
    You cold also use `collectingAndThen`: `list.stream().collect(collectingAndThen(groupingBy(s -> s), m -> new ArrayList<>(m.values())));` – Alexis C. May 01 '17 at 14:20
  • 1
    That is also a nice solution @AlexisC.! Neat substitute for streaming the values from the map. – Robin Topper May 01 '17 at 14:25