Sree
Sree

Reputation: 1758

How to achieve this scala operation in java efficiently

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 ???

Upvotes: 6

Views: 127

Answers (3)

dimo414
dimo414

Reputation: 48834

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

Upvotes: 2

toto2
toto2

Reputation: 5326

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.

Upvotes: 1

F. B&#246;ller
F. B&#246;ller

Reputation: 4294

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.

Upvotes: 3

Related Questions