Java 8 Streams:使用映射值列出要映射的列表 [英] Java 8 Streams: List to Map with mapped values

查看:73
本文介绍了Java 8 Streams:使用映射值列出要映射的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Stream 来自列表创建地图 code> s。

I'm trying to create a Map from a List using Streams.

应该是原始项目的名称,

The key should be the name of the original item,

应该是一些派生数据。

The value should be some derived data.

<$> c $ c> .map()该流由整数组成,并且在 .collect()<时/ code>我无法从之前的 lambda 访问foo。如何在 .toMap()中获取原始项目?

After .map() the stream consists of Integers and at the time of .collect() I can't access "foo" from the previous lambda. How do I get the original item in .toMap()?

可以使用<$ c $完成c> Stream s或我需要 .forEach()

Can this be done with Streams or do I need .forEach()?

(The下面的代码仅用于演示,真正的代码当然要复杂得多,我不能使 doSomething()一个 Foo的方法)。

(The code below is only for demonstration, the real code is of course much more complex and I can't make doSomething() a method of Foo).

import java.util.ArrayList;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class StreamTest {

    public class Foo {
        public String getName() {
            return "FOO";
        }

        public Integer getValue() {
            return 42;
        }
    }

    public Integer doSomething(Foo foo) {
        return foo.getValue() + 23;
    }

    public Map<String, Integer> run() {
        return new ArrayList<Foo>().stream().map(foo -> doSomething(foo)).collect(Collectors.toMap(foo.getName, Function.identity()));
    }

    public static void main(String[] args) {
        StreamTest streamTest = new StreamTest();
        streamTest.run();
    }
}


推荐答案

它在我看来它并不复杂。我错过了什么吗?

It appears to me it’s not that complicated. Am I missing something?

    return Stream.of(new Foo())
            .collect(Collectors.toMap(Foo::getName, this::doSomething));

我更喜欢方法参考。如果您更喜欢 - > 表示法,请使用

I’m rather much into method references. If you prefer the -> notation, use

    return Stream.of(new Foo())
            .collect(Collectors.toMap(foo -> foo.getName(), foo -> doSomething(foo)));

如果有多个 Foo,则会中断(抛出异常) / code>在您的信息流中使用相同的名称。

Either will break (throw an exception) if there’s more than one Foo with the same name in your stream.

这篇关于Java 8 Streams:使用映射值列出要映射的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆