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());
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.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
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.
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.
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)
It is extended your idea:
List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
.collect(Collectors.toList())
One more way of using lambda collectors like above answers
List<String> tmpAdresses= users
.stream()
.collect(Collectors.mapping(User::getAddress, Collectors.toList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With