与类和子类一起使用流的最佳方法
我在Java 8中使用流时遇到问题,我有3个这样的类:
I have a problem to use streams in java 8, I have 3 class like this:
public Class A {
String string1A;
String string2A;
List<B> listB;
.
.
.
}
public Class B {
String string1B;
String string2B;
.
.
.
}
public Class C {
String string1A;
String string2A;
String string1B;
String string2B;
.
.
.
}
然后,我有一个方法返回一个C
列表,其中所有数据都来自数据库,我需要创建一个将所有数据分组的列表A
,分组值为String1A
.我的想法是这样的:
Then I have a method that returns a List of C
with all the data coming from a database, and I need to create a List A
that has all the data grouped, the grouping value is the String1A
. My idea was this:
List<A> listA = new ArrayList<A>();
Set<String> listString1A = listC.stream().map(x->x.getString1A()).distinct().collect(Collectors.toSet());
for(String stringFilter1A: listString1A){
A a = listC.stream()
.filter(x->getString1A().equals(stringFilter1A))
.map(x-> new A(x.getString1A(),x.getString2A))
.findFirst().get();
List<B> listB = listC.stream()
.filter(x->getString1A().equals(stringFilter1A))
.map(x-> new B(...))
.collect(Collectors.toList());
a.setListB(listaB);
listaA.add(a);
}
是否有一种仅使用流或试图删除for进行查询的方法?
Is there a way to make such a query using only streams or trying to delete the for?
谢谢.
这是将c
元素按A
分组的一种方式,将每个C
映射到新的B
:
Here's a way that groups c
elements by A
, mapping each C
to a new B
:
Map<A, List<B>> map = listC.stream()
.collect(Collectors.groupingBy(
c -> new A(...), // construct new A instance out from c instance
Collectors.mapping(
c -> new B(...), // construct new B instance out from c instance
Collectors.toList())));
这需要类A
基于string1A
一致地实现hashCode
和equals
.
This requires class A
to implement hashCode
and equals
consistently, based on string1A
.
然后,您只需为地图中的每个A
设置List<B>
:
Then, you simply set the List<B>
for each A
in the map:
map.forEach((a, listB) -> a.setListB(listB));
地图键就是您想要的:
Set<A> setA = map.keySet();
或者如果您确实需要列表:
Or if you really need a list:
List<A> listA = new ArrayList<>(map.keySet());