我有以下几件事:
class AAA {
String A1;
String A2;
String A3;
String A4;
}
class BBB {
String A3;
String A4;
}
List<AAA> aaaList= new ArrayList<>(); // has 10 objects
我想用BBB对象填充第二个列表,以防A1和A2值相等。所以像这样:
List<BBB> bbbList = aaaList.stream().filter(obj -> obj.getA1().equals(obj.getA2())).map(obj -> new BBB(obj.getA3(), obj.getA4())).collect(Collectors.toList());
但是不知道这应该看起来如何工作...
问题来源:Stack Overflow
这是代码,在注释中有解释。
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//Note - Object.toString() was defined for AAA & BBB classes. Their member variables are public just to reduce code.
public class Test {
public static void main(String [] args){
//Generate some test data.
List<AAA> testData = Stream
.of(1,2,3,4,5)
.map(i -> new AAA(i+"", (i%3)+"", i*3+"", i*4+""))
.collect(Collectors.toList());//% is modulo operator.
System.out.println("Test data:\n");
testData.forEach(System.out::println);
List<BBB> processedData = testData
.stream()
//If a.A1 = a.A2, then allow it.
.filter(a -> a.A1.equals(a.A2))
//Take an AAA and convert it into a BBB.
.map(a -> new BBB(a.A3, a.A4))
//Collect all the BBBs and put them in a list.
.collect(Collectors.toList());
System.out.println("Processed data:\n");
processedData.forEach(System.out::println);
}
}
输出:
Test data:
AAA{A1='1', A2='1', A3='3', A4='4'}
AAA{A1='2', A2='2', A3='6', A4='8'}
AAA{A1='3', A2='0', A3='9', A4='12'}
AAA{A1='4', A2='1', A3='12', A4='16'}
AAA{A1='5', A2='2', A3='15', A4='20'}
Processed data:
BBB{A3='3', A4='4'}
BBB{A3='6', A4='8'}
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。