What is the Java equivalent for Enumerable.Select with lambdas in C#?

前端 未结 1 1431
遥遥无期
遥遥无期 2021-02-01 12:47

Say I have an object in C#:

public class Person
{
    public string Name{get;set;}
    public int Age{get;set;}
}

To select the names from this

相关标签:
1条回答
  • 2021-02-01 13:07

    If you have a list of Persons like List<Person> persons; you can say

    List<String> names
      =persons.stream().map(x->x.getName()).collect(Collectors.toList());
    

    or, alternatively

    List<String> names
      =persons.stream().map(Person::getName).collect(Collectors.toList());
    

    But collecting into a List or other Collection is intented to be used with legacy APIs only where you need such a Collection. Otherwise you would proceed using the stream’s operations as you can do everything you could do with a Collection and a lot more without the need for an intermediate storage of the Strings, e.g.

    persons.stream().map(Person::getName).forEach(System.out::println);
    
    0 讨论(0)
提交回复
热议问题