How to create this java comparator

java comparator lambda
comparator java example
java comparator example sort
java comparator vs comparable
anonymous comparator java
when to use comparable and comparator in java with example
inline comparator java
java 11 comparator

I have this class:

public class Test {

  private int    priority;
  private String desciption;
...
}

and I have this arraylist:

Priority: 1, Description: C2
Priority: 2, Description: C1
Priority: 3, Description: C1
Priority: 4, Description: C2

I want this result:

Priority: 1, Description: C2
Priority: 4, Description: C2
Priority: 2, Description: C1
Priority: 3, Description: C1

How I have to do this with comparator? Thank you!

EDIT:

I reply to all of your questions:

@retro: no. description is a string without a specific format. it can be empty, too.

@tobias_k: first "group" by description and than order by priority. priority is always not equals.

@user270349:

this is my try:

int result = 0;
if (o1.getPriority() < o2.getPriority()) result = -1;
else if (o1.getPriority() > o2.getPriority()) result = 1

result *= o1.getDescription().compareTo(o2.getDescription());

return result;

EDIT 2:

another input/output example:

and I have this arraylist:

Priority: 1, Description: C2
Priority: 2, Description: C3
Priority: 3, Description: C1
Priority: 4, Description: C2

I want this result:

Priority: 1, Description: C2
Priority: 4, Description: C2
Priority: 2, Description: C3
Priority: 3, Description: C1

THIS IS MY SOLUTION:

            List<Test> testList = new ArrayList<>();
    testList.add(new Test(4, "C2"));
    testList.add(new Test(2, "C3"));
    testList.add(new Test(3, "C1"));
    testList.add(new Test(1, "C2"));


    Comparator<Test> comparator = new Comparator<Test>() {

        @Override
        public int compare(Test o1, Test o2) {
            int res = o1.getDescription().compareTo(o2.getDescription());
            if (res == 0)
                return o1.getPriority() < o2.getPriority() ? -1 : 1;
            else
                return res;
        }
    };

    Collections.sort(testList, comparator);


    List<String> valoriInseriti = new ArrayList<>();
    List<Test> grouping = new ArrayList<>();
    for (Test t : testList) {
        if (!valoriInseriti.contains(t.getDescription())) {
            valoriInseriti.add(t.getDescription());
            grouping.add(t);
        }
    }


    comparator = new Comparator<Test>() {

        @Override
        public int compare(Test o1, Test o2) {
            return o1.getPriority() < o2.getPriority() ? -1 : 1;
        }
    };

    Collections.sort(grouping, comparator);


    Collections.sort(testList, comparator);

    List<Test> output = new ArrayList<>();
    for (Test t1 : grouping) {
        for (Test t2 : testList) {
            if (t2.getDescription().equals(t1.getDescription())) {
                output.add(t2);
            }
        }
    }

    System.out.println("==============================");
    for (Test t : output)
        System.out.println(t);

Test implements Comparator and override compare() method

  public class Test implements Comparator<Test>{
    private int    priority;
    private String desciption;

    @Override
    public int compare(Test o1, Test o2) {
       // your code here
    }

  }

Comparator Interface in Java with Examples, Comparator Interface in Java with Examples Java program to demonstrate working of Comparator create customer objects using constructor initialization. obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.


Comparator<Test> myComparator = new Comparator<Test>() {
    public int compare(Test o1, Test o2) {
        int result = o2.desciption.compareTo(o1.desciption);

        if (result == 0) {
            return o1.priority - o2.priority;
        }

        return result;

    }
};

List<Test> sortedList = Collections.sort(testList, myComparator);

Java Comparable and Comparator interface examples, Java Comparable interface intuition. By default, a user defined class is not comparable. That is, its objects can't be compared. To make  Let's see a quick example of how to use a lambda expression to create a Comparator: Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking(); The Comparator.comparing method takes a method calculating the property that will be used for comparing items, and returns a matching Comparator instance:


Comparator<Test> comparator = new Comparator<Test>() {

            @Override
            public int compare(Test o1, Test o2) {
                return o1.desciption.compareTo(o2.desciption);
            }
                  };

As, your problem specifies, you want to order the object of Test class in descending order with respect to description field, use Collections.reverseOrder(comparator)

Comparator<Test>reverse = Collections.reverseOrder(comparator);

Comparator and Comparable in Java, Next, let's create a PlayerSorter class to create our collection and make an attempt to sort it using Collections.sort: ? 1. 2. 3. 4. 5. 6. public interface Comparable<T> { public int compareTo(T o); }. When you define the compareTo() method in your classes, you need to make sure that the return value of this method is -. negative, if this object is less than the supplied object. zero, if this object is equal to the supplied object.


First thing you want to do is make your Test class implement Comparator.

public class Test implements Comparator<Test> {
    // Fields etc.

    public int compare(Test test1, Test test2)
    {
         // Add your logic in here.
         return test1.getDescription().compareTo(test2.getDescription()) * -1;
    }
}

This will work because String compares lexographically. It will attempt to sort in ascending order, in terms of the first letter. If the first letter is equal, it will move onto the next value. By reversing it, you can store in descending order.

Then you sort it, use Collections.sort(myList);. And here is a working ideone example: http://ideone.com/SdFGFg

Java - How to Use Comparator?, For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison. The equals Method. The equals( ) method, shown​  Save your file as GardenTool.java. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter. Next you will create the program to create various sets using Comparable and Comparator.


Do like this

Your TestComparator

class TestComparator implements Comparator<Test> {
    @Override
    public int compare(Test o1, Test o2) {

        String[] arr1 = o1.getDesciption().split("(?<=\\D)(?=\\d)");
        String[] arr2 = o2.getDesciption().split("(?<=\\D)(?=\\d)");
        if(Integer.parseInt(arr2[1])!=Integer.parseInt(arr1[1])){
            return  new Integer(Integer.parseInt(arr2[1])).compareTo(Integer.parseInt(arr1[1]));
        }
        if(o1.getPriority()!=o2.getPriority()){
           return   new Integer(o1.getPriority()).compareTo(o2.getPriority());
        }
        return 0;
    }    
}

your sorting

 System.out.println(list);      
 Collections.sort(list,new TestComparator());
 System.out.println("After sorting");
 System.out.println(list);

your output

[Test [priority=1, desciption=C2], Test [priority=2, desciption=C1], Test [priority=3, desciption=C1], Test [priority=4, desciption=C2]]
After sorting
[Test [priority=1, desciption=C2], Test [priority=4, desciption=C2], Test [priority=2, desciption=C1], Test [priority=3, desciption=C1]]

Java Comparator interface example, Using group by sort on list or array of objects on different fields. 1.1. Comparator.​compare(). To enable total ordering on objects, we need to create class which  Java Comparator interface used to sort a array or list of objects based on custom order. Custom ordering of elements is imposed by implementing Comparator.compare() method in the objects. 1. Java Comparator interface. Java Comparator interface imposes a total ordering on the objects which may not have a natural ordering.


Java Comparator, Java Comparator interface is used to order the user-defined class objects, compare() method, collection class In this example, we have created 4 java classes:. Method 2: Using comparator interface- Comparator interface is used to order the objects of user-defined class. This interface is present in java.util package and contains 2 methods compare (Object obj1, Object obj2) and equals (Object element). Using comparator, we can sort the elements based on data


Java object sorting example (Comparable and Comparator , 3. Sort an Object with Comparable. How about a Java Object? Let create a Fruit class: public class Fruit{ private String fruitName; private String  To make a redstone comparator, place 3 stones, 3 redstone torches, and 1 nether quartz in the 3x3 crafting grid. When making a redstone comparator, it is important that the stones, redstone torches, and nether quartz are placed in the exact pattern as the image below.


Sorting with Comparable and Comparator in Java, We've also overridden the toString() method, just to make the example easier to read. The toString method shows all the information from the object. When we print  A redstone comparator is removed and drops itself as an item if: its attachment block is moved, removed, or destroyed. water flows into its space.‌ [Java Edition only] a piston tries to push it or moves a block into its space. If lava flows into a redstone comparator's space, the redstone comparator is destroyed without dropping itself as an