使用 lambda 和流表达代码块的简洁方式

Succinct way to express a block of code using lambda and streams

您好,我有一段代码可以将一种 window 对象的列表转换为另一种类型,并将其填充到地图中,以 id 为键。可能有许多具有相同 ID 但具有不同名称和属性的对象实例。我正在做的是获取列表 [W1(1,2,3), W1(2,3,4), W2(1,3,4)...] 并将其转换为 映射 [ 键 W1 , 值 (1,2,3), (2,3,4) 键 W2, .... ]

这是代码片段...

    List<LinWin> list = winDao.get.....

    Map<Long, List<MacWin>> res = new HashMap<>();
    for (LinWin mw : list) {

        List<MacWin> l2 = res.get(mw.getId());
        if (l2 == null) {
            l2 = new ArrayList<>();
            res.put(mw.getId(), l2);
        }
        l2.add(new MacWin(mw.getName(), mw.getVendor(), mw.isFixed()));
    }

return 水

我想知道我是否可以使用流和 lambda 来折叠它。

list.stream().collect(Collectors.toMap(.....

这确实可以简化,例如,如果您有一个从 LinWin 转换为 MacWin 的方法(要么使其成为静态的,要么为 MacWin 创建一个构造函数,它将接受 LinWin 作为输入)。我将在这里生成一个静态方法:

private static MacWin of(LinWin lw){
    return new MacWin(mw.getName(), mw.getVendor(), mw.isFixed());
}

以后的用法是(我在这里不使用流,因为在这种情况下,在没有流的情况下做事对我来说看起来更容易):

Map<Long, List<MacWin>> res = new HashMap<>();
mw.forEach(x -> res.computeIfAbsent(mw.getId(), y -> new ArrayList<>()).add(of(x)));