Search code examples
javajava-8java-stream

How to get a new list from one list property in a list using the Java Stream API


I'm new to Java 8 and encountered a problem that troubles me a lot.

I have a List<objMain> like below:

List<objMain>

class objMain{
    Long rid;
    List<objUser> list;
    String rname;
}

class objUser{
    String userid;
}

Now I want to get a new List<objUserMain> like below:

List<objUserMain>

class objUserMain{
    Long rid;
    String rname;
    String userid;
}

How can I do this using the Java Stream API?


Solution

  • You can do this using streams the following way

    
    
        public static  List convert(List existing, Function func) {
            return existing.stream().map(func).collect(Collectors.toList());
        }
    
    

    The above method will help you to convert your list from one object type to another. The parameters to this is the initial object you want to convert and the method you want to use for conversion. Import the following in you main class

    
    
        import java.util.*;
        import java.util.stream.Collectors;
        import java.util.stream.Stream;
        import java.util.function.*;
    
    
    

    Now call the method for conversion the following way in the main class that you are trying to convert

    
    
        List result=convert(newList,
        l->{
        objUserMain r=new objUserMain();
        r.rid=l.rid;
        r.rname=l.rname;
        r.userid=l.list.get(0).userid;
        return r;});
        System.out.println(result.get(0).rid);
        System.out.println(result.get(0).rname);
        System.out.println(result.get(0).userid);
    
    
    

    The above is a mixture of lambda functions and streams to allow you to convert object from one type to another. Let me know if you have any queries then I am happy to help. Happy coding.