How to Reorder SortedSet

I want to print an ordered list on a Map using the following:

Map<Float, String> mylist = new HashMap<>(); mylist.put(10.5, a); mylist.put(12.3, b); mylist.put(5.1, c); SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet()); for (Float i : orderlist) { System.out.println(i+" "+mylist.get(i)); } 

The above code prints:

 5.1 c 10.5 a 12.3 b 

But how to print the list of orders in reverse order, as shown below:

 12.3 b 10.5 a 5.1 c 
+5
source share
3 answers

If you want to save the elements in the SortedSet in the reverse order, the only change you need to make is to build the TreeSet using the appropriate constructor , which the custom Comparator accepts:

 Map<Float, String> mylist = new HashMap<>(); mylist.put(10.5, a); mylist.put(12.3, b); mylist.put(5.1, c); SortedSet<Float> orderlist = new TreeSet<Float>(Collections.reverseOrder()); orderList.addAll(mylist.keySet()); for (Float i : orderlist) { System.out.println(i+" "+mylist.get(i)); } 

Note that the neat method here is Collections.reverseOrder() , which returns a Comparator that compares as opposed to the natural ordering of the elements.

+4
source

You can also try the following:

  Map<Float, String> mylist = new HashMap<Float, String>(); mylist.put(10.5, a); mylist.put(12.3, b); mylist.put(5.1, c); SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet()).descendingSet(); for (Float i : orderlist) { System.out.println(i+" "+mylist.get(i)); } 
+3
source

Try using NavigableSet :

  public NavigableSet<E> descendingSet() 

Like this:

  SortedSet<Float> orderlist = new TreeSet<Float>(mylist.keySet()); SortedSet<Float> treereverse = new TreeSet<Float>(); // creating reverse set treereverse=(TreeSet)orderlist.descendingSet(); 

Finally, you have a treereverse in reverse order.

+2
source

Source: https://habr.com/ru/post/1241965/


All Articles