Enumerable.Select 与 C# 中的 lambdas 的 Java 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19396944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the Java equivalent for Enumerable.Select with lambdas in C#?
提问by SamuelKDavis
Say I have an object in C#:
假设我在 C# 中有一个对象:
public class Person
{
public string Name{get;set;}
public int Age{get;set;}
}
To select the names from this list in C# I would do the following:
要在 C# 中从此列表中选择名称,我将执行以下操作:
List<string> names = person.Select(x=>x.Name).ToList();
How would I do the same thing in Java 8?
我将如何在 Java 8 中做同样的事情?
采纳答案by Holger
If you have a list of Persons like List<Person> persons;
you can say
如果你有一个像List<Person> persons;
你这样的人的名单可以说
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 String
s, e.g.
但是收集到 aList
或 otherCollection
旨在仅在您需要这样的Collection
. 否则,您将继续使用流的操作,因为您可以使用 a 做所有可以做的事情,Collection
而无需中间存储String
s,例如
persons.stream().map(Person::getName).forEach(System.out::println);