I wanted to filter list of Person class and finally map to some anonymous class in Java using Streams. I am able to do the same thing very easily in C#.
Person class
If you want to create a list of new Person
instances you first should provide a constructor, e.g. like this:
class Person {
public int id;
public String name;
public String address;
public Person( int pId, String pName, String pAddress ) {
super();
id = pId;
name = pName;
address = pAddress;
}
}
Then you could use the stream:
List lst = new ArrayList<>();
lst.add(new Person(1, "Pava", "India" ));
lst.add(new Person( 2, "tiwari", "USA" ) );
//since id is an int we can't use null and thus I used -1 here
List result = lst.stream().map(p -> new Person(-1, p.name, p.address)).collect(Collectors.toList());
If you want to filter persons then just put a filter()
in between stream()
and map()
:
List result = lst.stream().filter(p -> p.name.startsWith( "P" )).map(p -> new Person( -1, p.name, p.address )).collect(Collectors.toList());