Java – sort the (array) list in a specific order

I have a list of objects that I want to sort in a defined order

Before sorting:         After sorting:
orange                  white
white                   blue
green                   yellow
brown                   orange
yellow                  black
black                   brown
...                     ...

Is there such a simple way?

Edit:

I have to add a more complex... What if there can be more colors with the same name / cardinality? For the former, whitex, Whitey, whitez, blueA, blueB,... All whites must appear first than all yellow, not all yellow Is it still possible to solve this problem with a comparator? (I can't imagine...)

Solution

Yes, you can create a comparator to create sorting policies, or define the natural order of classes that implement comparable

As a side note:

Examples of using Comparators:

class MyClass {

private Color color;
private String someOtherProperty;
public static final Comparator<MyClass> colorComparator = new MyComparator();

//getter and setter

static class MyComparator implements Comparator<MyClass>{

            @Override
            public int compare(MyClass o1,MyClass o2) {
                // here you do your business logic,when you say where a color is greater than other
            }    
}

}

And in the client code

Example:

List<MyClass> list = new ArrayList<>();
//fill array with values
Collections.sort(list,MyClass.colorComparator );

Read more: collections #sort (..)

If you want to define the natural order of your classes, just define

public class MyClass implements Comparable<MyClass>{

        @Override
        public int compareTo(MyClass o) {
           // do business logic here
        }
}

And in the client code:

Collections.sort(myList); // where myList is List<MyClass>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>