Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda create list of Strings from list of objects

I have the following qustion:

How can I convert the following code snipped to Java 8 lambda style?

List<String> tmpAdresses = new ArrayList<String>();
for (User user : users) {
    tmpAdresses.add(user.getAdress());
}

Have no idea and started with the following:

List<String> tmpAdresses = users.stream().map((User user) -> user.getAdress());
like image 384
LStrike Avatar asked Aug 08 '18 13:08

LStrike


People also ask

How do I turn a List of objects into strings?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I get a List of fields from a List of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do I convert a List of elements to a String in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

How do you store String data in a List?

To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.


3 Answers

You need to collect your stream into a List:

List<String> adresses = users.stream()     .map(User::getAdress)     .collect(Collectors.toList()); 

For more information on the different Collectors visit the documentation

User::getAdress is just another form of writing (User user) -> user.getAdress() which could aswell be written as user -> user.getAdress() (because the type User will be inferred by the compiler)

like image 129
Lino Avatar answered Sep 25 '22 15:09

Lino


It is extended your idea:

List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
like image 36
Piotr Rogowski Avatar answered Sep 25 '22 15:09

Piotr Rogowski


One more way of using lambda collectors like above answers

 List<String> tmpAdresses= users
                  .stream()
                  .collect(Collectors.mapping(User::getAddress, Collectors.toList()));
like image 21
Oomph Fortuity Avatar answered Sep 22 '22 15:09

Oomph Fortuity