how do I join multiple list with varargs in java?

Viewed 148

I want to join several list using Stream API.

I found a useful example at stackoverflow:

List<Integer>list1=Arrays.asList(1,2,3);
List<Integer>list2=Arrays.asList(4,5,6);
List<Integer>list3=Arrays.asList(7,8,9);
List<Integer>list4=Arrays.asList(10,0,-1);

List<Integer> newList = 
    Stream.of(list1, list2, list3,list4)
          .flatMap(Collection::stream)
          .collect(Collectors.toList());       
System.out.println(newList); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, -1] 

Nice. But in my case, I can`t determine how many lists to use this Stream.of().

I thought about using varargs at jdk8. like this

public List<Integer> getNewList(List... list) {
    List<Integer> newList = 
         Stream.of(list)
               .flatMap(Collection::stream)
               .collect(Collectors.toList());
    return newList;
}

getNewList(list1, list2, list3, list...) 

Unfortunately, it didn`t work well. Is there a way to make this work?

3 Answers

You should specify the type of List parameters you are passing as var args, and you can also use Arrays.stream instead of Stream.of

 public static List<Integer> getNewList(List<Integer>... list){
    return Arrays.stream(list)
            .flatMap(List::stream)
            .collect(Collectors.toList());
}

Arrays.stream should do the trick:

public static <T> List<T> merge(List<T>... lists) {
    return Arrays.stream(lists)
                 .flatMap(List::stream)
                 .collect(Collectors.toList());

}

BTW, I've just noticed that your solution is almost fine. The only thing you need to add is <Integer>. So Stream.of should be also fine.

public List<Integer> getNewList(List<Integer>... list) {
    List<Integer> newList = 
         Stream.of(list)
               .flatMap(Collection::stream)
               .collect(Collectors.toList());
    return newList;
}

In fact, Stream::of calls Arrays::stream under the hood. So you can use any of them for your particular use case.

Try it like this. Use Arrays.stream() to stream the array of lists via the varargs syntax.

public static <T> List<T> getNewList(List<T>... list) {
    return  Arrays.stream(list).flatMap(Collection::stream)
                    .collect(Collectors.toList());
}
Related