我想使用Java Stream来遍历一个POJO的列表,例如下面的列表List<A>
,并将其转换为一个Map Map<String, Set<String>>
。
例如,类A如下:
class A {
public String name;
public String property;
}
我编写了下面的代码,将值收集到一个Map<String, String>
中:
final List<A> as = new ArrayList<>();
// the list as is populated ...
// works if there are no duplicates for name
final Map<String, String> m = as.stream().collect(Collectors.toMap(x -> x.name, x -> x.property));
然而,由于可能存在多个具有相同 name
的 POJO,我希望该映射的值为一个 Set
。所有具有相同键 name
的 property
字符串都应该放在同一个集合中。
如何实现?
// how do i create a stream such that all properties of the same name get into a set under the key name
final Map<String, Set<String>> m = ???
import static java.util.stream.Collectors.*;
。 - tkja