Java – a unique list of elements for a given list
Given the ArrayList transaction of sorted integer ArrayLists, I am writing code to return its unique element For example, given
transactions = [ [1,1,2,3,5,8,13,21],[2,6,10],[11,21] ]
My code should return unique elements, preserving the sort order:
[1,10,11,21]
To achieve this, I just add each element in each list to the linkedhashset, which maintains sorting and removes duplicates through its definition
Set<Integer> uniqEl = new LinkedHashSet<>(); for (List<Integer> l : transactions) { for (Integer n : l) { uniqEl.add(n); } }
Although my code works by using the Java library, I want to achieve a more efficient implementation Is there a better algorithm to generate a sorted list of unique elements from the list?
Solution
By using TreeSet and adding all lists to this collection, you will not be able to get more efficient content TreeSet will sort elements in ascending order according to their natural order and ignore duplicates
public static void main(String[] args) { List<List<Integer>> transactions = Arrays.asList(Arrays.asList(1,21),Arrays.asList(2,10),Arrays.asList(11,21)); SortedSet<Integer> set = new TreeSet<>(); for (List<Integer> l : transactions) { set.addAll(l); } }
Of course, you can use Java 8 streams for the following lines:
SortedSet<Integer> set = transactions.stream() .flatMap(List::stream) .collect(Collectors.toCollection(TreeSet::new));
With this solution, you can run it in parallel, but you must measure whether it can improve performance