Orange Receptacle
Orange Receptacle

Reputation: 1183

Java: Splitting array/list of elements into sublists of equal elements

Given a sorted List as such:

List<Integer> a = Arrays.asList(1, 1, 1, 2, 4, 5, 5, 7);

Would there be a single-line way of splitting this array into sublists, each containing elements of equal value, eg:

List[List[1, 1, 1], List[2], List[4], List[5, 5], List[7]]

Upvotes: 3

Views: 159

Answers (1)

Eran
Eran

Reputation: 393771

You can stream over the elements of the List and use Collectors.groupingBy() to group identical elements. It will produce a Map<Integer,List<Integer>>, and you can obtain the values() Collection:

Collection<List<Integer>> grouped =
    a.stream()
     .collect(Collectors.groupingBy(Function.identity()))
     .values();

To get a List<List<Integer>> you can use:

List<List<Integer>> grouped = 
    new ArrayList<> (a.stream()
                      .collect(Collectors.groupingBy(Function.identity()))
                      .values());

The second snippet produces the List:

[[1, 1, 1], [2], [4], [5, 5], [7]]

Upvotes: 7

Related Questions