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

前端 未结 4 1583
误落风尘
误落风尘 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 21:58

    If you know which attributes to select and this does not change, I would recommend writing a small class with that subset of Person's attributes. You can then map every person to an instance of that class and collect them into a list:

    Stream.of(new Person(1, "a", "aa"), new Person(2, "b", "bb"), new Person(3, "b", "bbb"),
              new Person(4, "c", "aa"), new Person(5, "b", "bbb"))
          .filter(person -> true)    // your filter criteria goes here
          .map(person -> new PersonSelect(person.getName(), person.getAddress()))
          .collect(Collectors.toList());
    
    // result in list of PersonSelects with your name and address
    

    If the set of desired attributes varies, you could use an array instead. It will look more similar to your C# code, but does not provide type safety:

    Stream.of(new Person(1, "a", "aa"), new Person(2, "b", "bb"), new Person(3, "b", "bbb"),
              new Person(4, "c", "aa"), new Person(5, "b", "bbb"))
          .filter(person -> true)
          .map(person -> new Object[] {person.getName(), person.getAddress()})
          .collect(Collectors.toList())
          .forEach(p -> System.out.println(Arrays.asList(p)));
    
    // output: [a, aa], [b, bb], [b, bbb], [c, aa], [b, bbb]
    

提交回复
热议问题