简体   繁体   中英

Java : use Streams to convert List<Object> to another List<anotherObject>

I have the below issue. I am familiar with traditional way to doing the below using java 7 but trying to accomplish this using java8 streams or forEach for better readability and less lines of code.

Object:

 public class Object {
   private String id;
   private String userName;
   private String address;
   private String email;
 //getters and setters
}

Now, i have a list of Objects like below:

List<Object> list = new ArrayList<>();
Object obj = new Object();
obj.setId(12);
obj.setUserName("myName");
obj.setAddress("address");
obj.setEmail("email");

Object obj1 = new Object();
obj1.setId(12);
obj1.setUserName("myName1");
obj1.setAddress("address1");
obj1.setEmail("email1");
list.add(obj);
list.add(obj1);

I have another Object User:

public class User {
      private String userName;
       private String address;
       private String email;
   //getters and setters
}

ResultObject:

public class ResultObject{
     private String id;
     private List<User> user;
   //getters and setters
}

Now For each Object in the list i want to groupThem by id and save the respective email,address and userName in User Object and finally want a List which has id mapped to a list of Users under the same Id.

So the ResultObject for above Example should be like:

id=12
List<User> = {["myname","address","email"],["myname1","address1","email1"]}

Any ideas are appreciated. TIA.

You can use the Collectors.mapping along with groupingBy of samples( Sample instead of Object ) to get an intermediate state of List<User> with the id they are associated to and them map each such entry to a ResultObject as:

List<ResultObject> resultObjects = samples.stream()
        .collect(Collectors.groupingBy(Sample::getId,
                Collectors.mapping(a -> new User(a.getUserName(), a.getAddress(), a.getEmail()),
                        Collectors.toList())))
        .entrySet().stream()
        .map(e -> new ResultObject(e.getKey(), e.getValue()))
        .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM