Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c#

java-8

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 list in C# I would do the following:

List<string> names = person.Select(x=>x.Name).ToList(); 

How would I do the same thing in Java 8?

like image 792
SamuelKDavis Avatar asked Oct 16 '13 06:10

SamuelKDavis


People also ask

Is there something like LINQ in Java?

There is nothing like LINQ for Java.

What is the equivalent of a function in Java?

In Java 8, the equivalents are the java. util. function. Function<T, R> and java.


1 Answers

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); 
like image 169
Holger Avatar answered Sep 28 '22 06:09

Holger