How can I turn a List of Lists into a List in Java 8?

后端 未结 9 791
春和景丽
春和景丽 2020-11-22 04:49

If I have a List>, how can I turn that into a List that contains all the objects in the same iteration order
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:29

    Just as @Saravana mentioned:

    flatmap is better but there are other ways to achieve the same

     listStream.reduce(new ArrayList<>(), (l1, l2) -> {
            l1.addAll(l2);
            return l1;
     });
    

    To sum up, there are several ways to achieve the same as follows:

    private  List mergeOne(Stream> listStream) {
        return listStream.flatMap(List::stream).collect(toList());
    }
    
    private  List mergeTwo(Stream> listStream) {
        List result = new ArrayList<>();
        listStream.forEach(result::addAll);
        return result;
    }
    
    private  List mergeThree(Stream> listStream) {
        return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
            l1.addAll(l2);
            return l1;
        });
    }
    
    private  List mergeFour(Stream> listStream) {
        return listStream.reduce((l1, l2) -> {
            List l = new ArrayList<>(l1);
            l.addAll(l2);
            return l;
        }).orElse(new ArrayList<>());
    }
    
    private  List mergeFive(Stream> listStream) {
        return listStream.collect(ArrayList::new, List::addAll, List::addAll);
    }
    

提交回复
热议问题