1

I am trying to sort a list in reverse order and then removing duplicates. I am using the following code.

 public static void main(String[] args) {
     List<Integer> list = new ArrayList<>();
     list.add(3);
     list.add(3);
     list.add(2);
     list.add(3);
     list.add(2);
     Collections.sort(list, Collections.reverseOrder());
     System.out.println(list);
     Set<Integer> set = new HashSet<>(list);
     System.out.println(set);
 }

It works fine but the order is again changed when converted to a Set. What to do to preserve the order

station
  • 5,659
  • 11
  • 47
  • 83

2 Answers2

2

Use a LinkedHashSet instead of a HashSet.

Set<Integer> set = new LinkedHashSet<>(list);

Unlike normal sets which have no guarantee of order, LinkedHashSets enforce insertion order. Since you've already sorted the list, you don't require any of the extra benefits which a TreeSet would provide (which orders based on natural ordering or an ordering of your own choosing).

Makoto
  • 96,408
  • 24
  • 164
  • 210
1

Instead of HashSet use TreeSet , the access time is less O(log(n)) instead of O(1) but it keeps the order of the keys

https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

Amer Qarabsa
  • 5,678
  • 3
  • 16
  • 31