Home > Net >  Is there a better way to compare and sort objects in list?
Is there a better way to compare and sort objects in list?

Time:06-13

Is there a better way to compare and sort objects in list?

here is example of class and simple comperator

class Zadanie{
    public int id;
    public String name;
    public String type;
    public int priority;
    public Date date;
    public boolean isDone;
}

Collections.sort(zadania, new Comparator<Zadanie>() {
                            @Override
                            public int compare(Zadanie o1, Zadanie o2) {
                                return Integer.valueOf(o2.priority).compareTo(o1.priority);
                            }

                        });

CodePudding user response:

When sorting lists, prefer List.sort for simplicity. When comparing primitives, use the comparingInt (or other suitable) method and use it with a method reference of your getter.

You can then sort a list of any objects with the same basic format:

list.sort(Comparator.comparingInt(MyClass::getPropertyToSortWith));

CodePudding user response:

Not really, only code can ble slightly shorter using lambdas

Collections.sort(zadania,Comparator.comparing(Zadanie::getPriority));

or something like this.

CodePudding user response:

You can also sort your list with JAVA-8 Stream-API:

List<Zadanie> sortedList = zadanieDtoList.stream()
  .sorted(Comparator.comparing(Zadanie::getName).reversed())
  .collect(Collectors.toList());

Here I sort the collection based on a specific variable, which is Name!!

  •  Tags:  
  • java
  • Related