2

有没有一种简单的方法通过仅将彼此相邻的重复元素分组来将列表拆分为子列表?

带有以下字符串列表的简单示例:

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

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

如果我从 java 流中使用 groupingBy,那么所有相等的元素都将最终出现在同一个子列表中,我想避免这种情况。有任何想法吗?

4

2 回答 2

3

您可以创建自定义收集器:

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;}));
于 2020-03-06T18:10:13.187 回答
2

我确信有一个更好的方法可以用流来做到这一点,但是为了快速而肮脏:

List<String> values = Arrays.asList("RED", "RED", "BLUE", "BLUE", "BLUE", "BLUE", "RED", "RED");
    List<List<String>> output = new ArrayList<List<String>>();
    String previous = null;
    List<String> subList = new ArrayList<String>();
    for (String value : values) {
        if (previous == null || value.equals(previous)) {
            subList.add(value);
        } else {
            output.add(subList);
            subList = new ArrayList<String>();
            subList.add(value);
        }
        previous = value;
    }
    if (!subList.isEmpty()) {
        output.add(subList);
    }
    System.out.println(output);
于 2020-03-06T17:18:58.340 回答