Java 8 Streams: List to Map with mapped values

前端 未结 1 1283
猫巷女王i
猫巷女王i 2021-01-13 19:26

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

The key should be the name of the original item,

T

相关标签:
1条回答
  • 2021-01-13 20:06

    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)));
    

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

    0 讨论(0)
提交回复
热议问题