[英]How can I convert a Set of objects into a Map of the Object's fields to a set of fields using Java streams?
If I have some class A 如果我有A班
public class A {
String name;
String value;
}
I have a Set which I want to convert into a Map<String, Set<String>>
, which maps A.name to a set of A.value, using the stream class, since many instances of A will share the same name String, but none will share the same value String. 我有一个要转换为
Map<String, Set<String>>
,它使用流类将A.name映射到A.value的集合,因为A的许多实例将共享相同的名称String ,但没有一个共享相同的字符串值。 Is there a way to do this? 有没有办法做到这一点?
To create a Map<String, Set<String>>
, which maps A.name
to a set of A.value
, you need to use the following methods: 要创建
Map<String, Set<String>>
,它映射A.name
一组A.value
,你需要使用下面的方法:
groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
Map<String, Set<String>> map = set.stream()
.collect(Collectors.groupingBy(A::getName,
Collectors.mapping(A::getValue,
Collectors.toSet())));
The code uses method references to getter methods on your A
class, though lambda expressions can be used instead, eg A::getName
could be replaced with o -> o.name
. 该代码使用方法引用来引用
A
类上的getter方法,尽管可以使用lambda表达式代替,例如A::getName
可以替换为o -> o.name
。
您可以在转换之前实例化一个空的Map,然后将使用匿名函数收集转换,该函数将检查该Map以查看它是否应该放置一个新集合或更新一个现有集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.