如何使用Java 8 Streams连接2元组中的数据?

时间:2016-10-26 07:39:42

标签: java java-8

我的数据如下:

[{"key1" : "a", "key2" : "1"}, {"key1" : "b", "key2" : "2"}, {"key1" : "a", "key2" : "3"}, {"key1" : "c", "key2" : "4"}, {"key1" : "b", "key2" : "5"}, {"key1" : "a", "key2" : "6"}]

我想连接它,看起来像这样:

[{"key1" : "a", "key3" : "1, 3, 6"}, {"key1" : "b", "key3" : "2, 5"}, {"key1" : "c", "key3" : "4"}]

我的课程是:

import lombok.Data;
@Data
class Person {
  String key1;
  String key2;
  String key3;
}

我试过这个:

Map<String, List<String>> byKey1 =
    data
        .stream()
        .collect(
            Collectors.groupingBy(Person::getKey1));

如何使用Java 8 Stream API执行此操作?

0 个答案:

没有答案