[英]What is the Java equivalent for Enumerable.Select with lambdas in C#?
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 中做同样的事情?
If you have a list of Persons like List<Person> persons;
如果你有一个像
List<Person> persons;
people 这样的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
.但是收集到
List
或其他Collection
旨在仅在您需要此类Collection
与遗留 API 一起使用。 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, eg否则,您将继续使用流的操作,因为您可以使用
Collection
做所有可以做的事情,而无需中间存储String
s,例如
persons.stream().map(Person::getName).forEach(System.out::println);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.