繁体   English   中英

Java 8流分组按字符串值

[英]Java 8 stream groupingBy String value

我有一个JSON文件,其中包含以下形式的数据:

{
    "type":"type1",
    "value":"value1",
    "param": "param1"
}
{
    "type":"type2",
    "value":"value2",
    "param": "param2"
}

我也有这样的对象:

public class TestObject {
    private final String value;
    private final String param;

    public TestObject(String value, String param) {
        this.value = value;
        this.param = param;
    }
}

我要创建一个Map<String, List<TestObject>> ,其中包含每种类型的TestObject列表。

这是我编写的代码:

Map<String, List<TestObject>> result = jsonFileStream
                .map(this::buildTestObject)
                .collect(Collectors.groupingBy(line -> JsonPath.read(line, "$.type")));

方法buildTestObject在哪里:

private TestObject buildTestObject(String line) {
    return new TestObject(
               JsonPath.read(line, "$.value"),
               JsonPath.read(line, "$.param"));
}

这不起作用,因为map()函数返回TestObject ,因此collect函数不再适用于JSON String行。

在现实生活中,我无法将“ type”变量添加到TestObject文件,因为它是来自外部库的文件。

如何按JSON文件中的类型对TestObject分组?

您可以将映射操作移至groupingBy的下游收集器:

Map<String, List<TestObject>> result = jsonFileStream
    .collect(Collectors.groupingBy(line -> JsonPath.read(line, "$.type"),
        Collectors.mapping(this::buildTestObject, Collectors.toList())));

这将保留字符串,以便您可以提取类型作为分类器,并将映射应用于结果组的元素。

您也可以使用toMap收集器完成手头的任务。

Map<String, List<TestObject>> resultSet = jsonFileStream
           .collect(Collectors.toMap(line -> JsonPath.read(line, "$.type"),
                  line -> new ArrayList<>(Collections.singletonList(buildTestObject(line))),
                  (left, right) -> {
                      left.addAll(right);
                      return left;
                 }
           ));

除了Stream解决方案外,值得指出的是Java 8还显着改进了Map接口,这使得使用for循环实现这种事情比以前for轻松得多。 我不熟悉您正在使用的库,但是类似的东西会起作用(您可以始终将Stream转换为Iterable )。

Map<String, List<TestObject>> map = new HashMap<>();
for (String line : lines) {
    map.computeIfAbsent(JsonPath.read(line, "$.type"), k -> new ArrayList<>())
       .add(buildTestObject(line)); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM