在C#中,带有lambdas的Enumerable.Select的Java等效项是什么? [英] What is the Java equivalent for Enumerable.Select with lambdas in C#?
问题描述
说我在C#中有一个对象:
Say I have an object in C#:
public class Person
{
public string Name{get;set;}
public int Age{get;set;}
}
要在C#中从此列表中选择名称,请执行以下操作:
To select the names from this list in C# I would do the following:
List<string> names = person.Select(x=>x.Name).ToList();
在Java 8中我将如何做同样的事情?
How would I do the same thing in Java 8?
推荐答案
如果您有诸如List<Person> persons;
之类的人物列表,您可以说
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());
或者,或者
List<String> names
=persons.stream().map(Person::getName).collect(Collectors.toList());
,但是收集到List
或其他Collection
的意图是仅在需要这样的Collection
的情况下才与旧版API一起使用.否则,您将继续使用流的操作,因为您可以使用Collection
完成所有操作,而无需中间存储String
例如
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 String
s, e.g.
persons.stream().map(Person::getName).forEach(System.out::println);
这篇关于在C#中,带有lambdas的Enumerable.Select的Java等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!