0

I've been googling for this, and I found this answer. There is an Iterables.concat in guava. But this returns an Iterable and the next thing I want to do is sort the result. Collections.sort takes in a List, not an Iterable so I'd have to convert the Iterable into a List as my next step. Is there a more direct way to combine two Lists and then sort the result?

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356

7 Answers7

6

In Java 8:

List<E> sorted = Stream.concat(l1.stream(), l2.stream())
                       .sorted()
                       .collect(Collectors.toList());
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
4
List<Something> list = Lists.newArrayList(Iterables.concat(...));
Collections.sort(list);

might be a solution here.

3

List has the addAll(Collection) method, which I think is useful for your purpose. You can copy the first list and make something like this:

copyList1.addAll(list2);
yshavit
  • 42,327
  • 7
  • 87
  • 124
2

If a SortedSet is also good as return type (I find this is one you really want in most cases) you can do:

FluentIterable.from( list1 ).concat( list2 ).toSortedSet( Ordering.natural() );
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
1

You can use

List<Something> list1;
List<Something> list2;

list1.addAll(list2);
Collections.sort( list1 );

(Assuming your list is a list of Comparables)

If you don't want to modify list1, you can use:

List<Something> list3 = new ArrayList<>();
Collections.copy( list3, list1 );
list3.addAll( list2 );
Collections.sort( list3 );
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
1

In Java 8 (replace String with whatever type your list contains):

List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).collect(Collectors.<String>toList());

This will concatenate your two lists to create a new, 3rd list. You can then sort it as you mentioned in your post by using Collections.sort:

Collections.sort(newList);

See also: How do I join two lists in Java?

Community
  • 1
  • 1
Christian Wilkie
  • 3,693
  • 5
  • 34
  • 49
1

The following should work with JAVA 8 Stream API

class T {
     @Getter private int sortingProperty; 
    }
 List<T> list3 Stream.of(list1OfT,list2OfT)    
                                 .sorted(Comparing(T::getSortingProperty))
                                 .collect(toList());
iamiddy
  • 3,015
  • 3
  • 30
  • 33