C#lambda在java 8中选择 [英] C# lambda select in java 8

查看:124
本文介绍了C#lambda在java 8中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在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?

推荐答案

如果您有列表< Person>等人员列表人; 你可以说

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

或者

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

但收集到列表或其他 Collection 仅用于需要 Collection 的旧版API。否则,您将继续使用流的操作,因为您可以使用集合执行所有操作,而不需要 String s,例如

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);

这篇关于C#lambda在java 8中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆