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

前端 未结 4 1618
误落风尘
误落风尘 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:11

    Well, you can map Person instances to instances of anonymous classes, e.g. assuming

    class Person {
        int id;
        String name, address;
    
        public Person(String name, String address, int id) {
            this.id = id;
            this.name = name;
            this.address = address;
        }
        public int getId() {
            return id;
        }
        public String getName() {
            return name;
        }
        public String getAddress() {
            return address;
        }
    }
    

    you can do

    List lst = Arrays.asList(
                           new Person("Pava", "India", 1), new Person("tiwari", "USA", 2));
    List result = lst.stream()
        .map(p -> new Object() { String address = p.getAddress(); String name = p.getName(); })
        .collect(Collectors.toList());
    

    but as you might note, it’s not as concise, and, more important, the declaration of the result variable can’t refer to the anonymous type, which makes the instances of the anonymous type almost unusable.

    Currently, lambda expressions are the only Java feature that supports declaring variables of an implied type, which could be anonymous. E.g., the following would work:

    List result = lst.stream()
        .map(p -> new Object() { String address = p.getAddress(); String name = p.getName(); })
        .filter(anon -> anon.name.startsWith("ti"))
        .map(anon -> anon.address)
        .collect(Collectors.toList());
    

提交回复
热议问题