My goal: Take a LinkedList
of User
s and extract a LinkedList
of their usernames in an elegant, Java-8 way.
public static void main(String[] args) { LinkedList<User> users = new LinkedList<>(); users.add(new User(1, "User1")); users.add(new User(2, "User2")); users.add(new User(3, "User3")); // Vanilla Java approach LinkedList<String> usernames = new LinkedList<>(); for(User user : users) { System.out.println(user.getUsername()); usernames.add(user.getUsername()); } System.out.println("Usernames = " + usernames.toString()); // Java 8 approach users.forEach((user) -> System.out.println(user.getUsername())); LinkedList<String> usernames2 = users.stream().map(User::getUsername). // Is there a way to turn this map into a LinkedList? System.out.println("Usernames = " + usernames2.toString()); } static class User { int id; String username; public User() { } public User(int id, String username) { this.id = id; this.username = username; } public void setUsername(String username) { this.username = username; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public int getId() { return id; } }
I am stuck trying to convert the Stream
object into a LinkedList
. I could turn it into an array (Stream::toArray()
) and turn that into a List
(Arrays.asList(Stream::toArray())
) but that just seems so... no thank you.
Am I missing something?
Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source. Algorithm: Get the Stream.
This class has the toList() method, which converts the Stream to a List.
Introduction. A linked list is a data structure where one object refers to the next one in a sequence by storing its address. Each object is referred to as a node. In addition to a reference to the next object in the sequence, each object carries some data (e.g., integer value, reference to string, etc.).
You can use a Collector
like this to put the result into a LinkedList
:
LinkedList<String> usernames2 = users.stream() .map(User::getUsername) .collect(Collectors.toCollection(LinkedList::new));
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