Skip to content
Advertisement

Append list according to their size in Java

I am trying to append two list according to their size. With list with bigger size in front.

I have few lists like this.

List<Pair<Double, String>> masterList = new ArrayList<>();

and this is the working Java code that I tried first – with a simple if else loop:

       if (listOne.size() >= listTwo.size()){
           masterList.addAll(listOne);
           masterList.addAll(listTwo);
       } else {
           masterList.addAll(listTwo);
           masterList.addAll(listOne);
       }
       masterList.addAll(otherList); // and at the end all other list can be added without any condition

I am fairly new to the Java, so I was studying about it and came across Comparators and Lambda. So, I tried to use that for my code, something like this:

List<Pair<Double, String>> masterList = Stream.concat(listOne.stream(), listTwo.stream())
                .filter(Comparator.comparingInt(List::size))
                .collect(Collectors.toList())

But I am not able to achieve proper results. Can someone point out my mistake, I am still trying to learn.

Advertisement

Answer

The for-loop is very nice, Stream isn’t necessary, but to answer the question, you may

  • not use concat as it’ll already join the lists, and you loose the concept of different list
  • don’t use filter but rather sorted
  • then flatMap to pass from Stream<List<Pair<>>> to Stream<Pair<>>
List<Pair<Double, String>> masterList = Stream.of(listOne, listTwo)
        .sorted(Comparator.comparing(List::size, Comparator.reverseOrder()))
        .flatMap(List::stream)
        .collect(Collectors.toList());
masterList.addAll(otherList);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement