Java 8 Streams:使用映射值列出要映射的列表

lil*_*nux 3 java-stream

我试图创建一个MapList使用Stream秒.

key应是原来的项目名称,

value应该是一些派生的数据.

.map()流由Integers 组成之后,当.collect()我无法从前一个访问"foo"时lambda.如何获取原始项目.toMap()

这可以用Streams 来完成还是我需要.forEach()

(下面的代码仅用于演示,实际代码当然要复杂得多,我无法制作doSomething()方法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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*.V. 6

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

    return Stream.of(new Foo())
            .collect(Collectors.toMap(Foo::getName, this::doSomething));
Run Code Online (Sandbox Code Playgroud)

我更喜欢方法参考.如果您更喜欢这种->符号,请使用

    return Stream.of(new Foo())
            .collect(Collectors.toMap(foo -> foo.getName(), foo -> doSomething(foo)));
Run Code Online (Sandbox Code Playgroud)

如果Foo您的流中有多个具有相同名称的内容,则会中断(抛出异常).