3

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]]

1 Answer 1

7

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.