Qazzablanca
Qazzablanca

Reputation: 1

Sorting a generic list of two types

  List.add(new TheDList("abc123", 9986));
  List.add(new TheDList("ads314", 9986));
  List.add(new TheDList("dal192", 3214));
  List.add(new TheDList("sam273", 3214));
  List.add(new TheDList("wor213", 7643));
  List.add(new TheDList("wos987", 1292));
  List.add(new TheDList("cat202", 9986));
  List.add(new TheDList("jga213", 1292));
  List.add(new TheDList("gog113", 1493));
  List.add(new TheDList("aba231", 9831)); 

There's a Class called TheDList and it has the name and value as final variables, but it also has a constructor and (get) methods.

The list above is from a method called sort and the elements in the list above are shuffled before the list is sent to me through this method.

there are two methods within the Class TheDList, getValue and getString how do I sort this using Collector or sort methods within Java?

Upvotes: 0

Views: 137

Answers (1)

Bohemian
Bohemian

Reputation: 424993

Use the reversed() method of Comparator to sort descending and employ the thenComparing() method to break ties.

Using Comparator methods, it’s a one-liner:

public void sort(List<TheDList> list) {
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
}

To leave the original list unchanged and instead return a new, sorted list, use ArrayList’s copy constructor before sorting:

public List<TheDList> sort(List<TheDList> list) {
    list = new ArrayList(list);
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
    return list;
}

Upvotes: 1

Related Questions