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?
Asked
Active
Viewed 1,522 times
0
Community
- 1
- 1
Daniel Kaplan
- 58,382
- 45
- 210
- 318
-
3`Lists.newArrayList(Iterables.concat(...))`? – Feb 04 '15 at 18:45
-
@RC. I'd accept that as the answer – Daniel Kaplan Feb 04 '15 at 18:56
-
1added as an answer (wasn't sure I understood the question, so I commented) – Feb 04 '15 at 19:11
-
possible duplicate of [How do I join two lists in Java?](http://stackoverflow.com/questions/189559/how-do-i-join-two-lists-in-java) – Raedwald Feb 05 '15 at 07:51
-
@Raedwald one minor difference is his question says, "no external libraries" – Daniel Kaplan Feb 05 '15 at 21:18
7 Answers
6
In Java 8:
List<E> sorted = Stream.concat(l1.stream(), l2.stream())
.sorted()
.collect(Collectors.toList());
Jean Logeart
- 50,693
- 11
- 81
- 116
4
List<Something> list = Lists.newArrayList(Iterables.concat(...));
Collections.sort(list);
might be a solution here.
-
3Shorter and likely faster: `Ordering.natural().sortedCopy(Iterables.concat(...))` – Louis Wasserman Feb 05 '15 at 00:48
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
- 41,077
- 7
- 83
- 120
Daniel Facciabene
- 93
- 1
- 6
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
- 22,652
- 17
- 122
- 191
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,227
- 7
- 50
- 77
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,491
- 5
- 30
- 47
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
- 2,955
- 3
- 27
- 33