I use List(1, 2, 3, 4) ::: List(1, 2, 5) distinct
for this issue. It returns List(1, 2, 3, 4, 5)
.
How to achieve the same functionality in java and do it very efficiently and elegantly ???
Use a SortedSet
instead of a List
to avoid duplicates and have an ordering.
Use
set.addAll (otherSet);
to add another Set
.
All in all:
TreeSet<Integer> set = new TreeSet<>();
set.addAll (Arrays.asList (1,2,3,4));
set.addAll (Arrays.asList (1,2,5));
Well, that's the elegant way. Since you have to use wrapper classes for int
here, it is maybe not as efficient as you want.
Almost certainly, Scala is internally simply converting this structure into a set in order to provide the distinct
behavior. As suggested, using a TreeSet
or a LinkedHashSet
(the latter, I suspect, will be faster), will work fine. Another option, if you're interested in how to efficiently write this, is with the fabulous Guava library.
List<Integer> distinctLs = new ImmutableSet.Builder<Integer>()
.addAll(listOne).addAll(listTwo)
.build().asList();
In particular, Guava's immutable collections are able to make many internal optimizations. For instance their immutable hash collections (ImmutableSet
, ImmutableMap
, etc.) preserve insertion order, and the .asList()
call returns a view in O(1), rather than needing to construct a whole new list in O(n).
Guava also lets you construct lists concisely, with ImmutableList.of(1,2,3,4)
.
Java 8 is functional too (somewhat):
IntStream stream1 = IntStream.builder().add(1).add(2).add(3).add(4).build();
IntStream stream2 = IntStream.builder().add(1).add(2).add(5).build();
IntStream concatStream = IntStream.concat(stream1, stream2).distinct();
concatStream.forEach(x -> System.out.println(x));
I have not used it much; I could not find a simpler way to create an IntStream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With