Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a stream of objects into a linked list of attributes

My goal: Take a LinkedList of Users 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?

like image 219
ryvantage Avatar asked Mar 25 '14 22:03

ryvantage


People also ask

How do you convert a List of objects into a Stream of objects?

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.

Which method is used to convert Stream to List?

This class has the toList() method, which converts the Stream to a List.

Can you have a linked list of objects?

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.).


1 Answers

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)); 
like image 114
Keppil Avatar answered Sep 26 '22 21:09

Keppil