Reputation: 67360
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 List
s and then sort the result?
Upvotes: 0
Views: 2966
Reputation:
List<Something> list = Lists.newArrayList(Iterables.concat(...));
Collections.sort(list);
might be a solution here.
Upvotes: 4
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
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
Reputation: 53819
In Java 8:
List<E> sorted = Stream.concat(l1.stream(), l2.stream())
.sorted()
.collect(Collectors.toList());
Upvotes: 6
Reputation: 34628
You can use
List<Something> list1;
List<Something> list2;
list1.addAll(list2);
Collections.sort( list1 );
(Assuming your list is a list of Comparable
s)
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
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
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