split a list into sublists by grouping **only** repeated elements that are adjacent to each other

wannaBeDev :

Is there a simple way to split a list into sublists by grouping only repeated elements that are adjacent to each other?

Simple example with the folowing list of strings:

Input:  [RED,RED,BLUE,BLUE,BLUE,GREEN,BLUE,BLUE,RED,RED]

Output:  [[RED,RED],[BLUE,BLUE,BLUE],[GREEN],[BLUE,BLUE],[RED,RED]]

If I use groupingBy from java streams all elements which are equal will end up in the same sublist, which I want to avoid. Any ideas?

Eng.Fouad :

You can create a custom collector:

List<String> input = Arrays.asList("RED", "RED", "BLUE", "BLUE", "BLUE", "BLUE", "RED", "RED");
List<List<String>> output = input.stream()
                                  .collect(Collector.of(ArrayList::new, (accumulator, item) ->
                                  {
                                      if(accumulator.isEmpty())
                                      {
                                          List<String> list = new ArrayList<>();
                                          list.add(item);
                                          accumulator.add(list);
                                      }
                                      else
                                      {
                                          List<String> last = accumulator.get(accumulator.size() - 1);
                                          if(last.isEmpty() || last.get(0).equals(item)) last.add(item);
                                          else
                                          {
                                              List<String> list = new ArrayList<>();
                                              list.add(item);
                                              accumulator.add(list);
                                          }
                                      }
                                  }, (left, right) -> {left.addAll(right); return left;}));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31347&siteId=1