What is equivalent to C#'s Select clause in JAVA's streams API

前端 未结 4 1607
误落风尘
误落风尘 2020-12-31 21:38

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

4条回答
  •  自闭症患者
    2020-12-31 22:14

    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());
    

提交回复
热议问题