How to use java 8 streams to make a new list by using another's list objects values with filter?

laklaklak :

I have the following things:

class AAA {
  String A1;
  String A2;
  String A3;
  String A4;
}

class BBB {
  String A3;
  String A4;
}


List<AAA> aaaList= new ArrayList<>(); // has 10 objects

I want to fill up the second list with BBB objects in case A1 and A2 values are equals. So something like this:

List<BBB> bbbList = aaaList.stream().filter(obj -> obj.getA1().equals(obj.getA2())).map(obj -> new BBB(obj.getA3(), obj.getA4())).collect(Collectors.toList());

But no idea how exactly this should look like to work...

WJS :

Presuming that the classes have the appropriate getters, setters. The constructors take the arguments in sequence.

So This:

List<AAA> listAAA =
        new ArrayList<>(List.of(new AAA("1", "2", "3", "4"),
                new AAA("1", "1", "30", "40"),
                new AAA("5", "6", "3", "4"),
                new AAA("1", "2", "3", "4"),
                new AAA("4", "4", "50", "60")));
List<BBB> listBBB = listAAA.stream()
        .filter(ob -> ob.getA1().equals(ob.getA2()))
        .map(ob -> new BBB(ob.getA3(), ob.getA4()))
        .collect(Collectors.toList());
System.out.println(listBBB);

Would print this:

[BBB [A3=30, A4=40], BBB [A3=50, A4=60]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238249&siteId=1