Daniel Kaplan
Daniel Kaplan

Reputation: 67360

How do I concatenate two lists to create a 3rd?

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?

Upvotes: 0

Views: 2966

Answers (7)

user180100
user180100

Reputation:

List<Something> list = Lists.newArrayList(Iterables.concat(...));
Collections.sort(list);

might be a solution here.

Upvotes: 4

iamiddy
iamiddy

Reputation: 3073

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());

Upvotes: 1

Daniel Facciabene
Daniel Facciabene

Reputation: 101

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);

Upvotes: 3

Jean Logeart
Jean Logeart

Reputation: 53819

In Java 8:

List<E> sorted = Stream.concat(l1.stream(), l2.stream())
                       .sorted()
                       .collect(Collectors.toList());

Upvotes: 6

RealSkeptic
RealSkeptic

Reputation: 34628

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 );

Upvotes: 1

Christian Wilkie
Christian Wilkie

Reputation: 3823

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?

Upvotes: 1

Wim Deblauwe
Wim Deblauwe

Reputation: 26858

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() );

Upvotes: 2

Related Questions