Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 994
Sree Avatar asked Jun 12 '14 16:06

Sree


3 Answers

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.

like image 88
F. Böller Avatar answered Nov 02 '22 22:11

F. Böller


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

like image 43
dimo414 Avatar answered Nov 02 '22 22:11

dimo414


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.

like image 21
toto2 Avatar answered Nov 02 '22 21:11

toto2