What is the equivalent method in Java for displaying in haskell or C #?

Is there a built-in function in Java that is similar to the display function in Haskell or Schema or the Select extensor method in C #? I just want to write code like this shorter:

List<String> names = new ArrayList<String>();
foreach (User element : getUsers()) {
   names.add(element.getName());
};
return names; 

      

shorter way (in C #)

List<String> names = getUsers().Select(x => x.getName()).ToList();

      

I also need a way to pass the function as a parameter in a "friendly" way.

+3


source to share


2 answers


In Java 8, it would look like



import static java.util.stream.Collectors.toList;

List<String> names = getUsers().stream().map(User::getName).collect(toList());

      

+5


source


Using streams in Java 8, you can do the following:



List<String> names = getUsers().stream().map(User::getName).collect(Collectors.toList())

      

-2


source







All Articles