Comparator based on a configurable order

java enum sort alphabetically
java list sort(comparator)
java comparator
java 8 sort list of objects
java sort list of objects by date property
sort list of objects in java without comparator
java compound comparator
date comparator java 8

Is there a way to write custom comparator, following this example:

There are at most 10 items coming in at a random order i.e.

first item:  item_one
second:      second_one
third:       third_one

I want result them to be sorted like : second_one, third_one, first_one. I'd like to pull this order from configuration file, sort of like template for sorting.

Am I using the wrong data structure, does anyone have experience with this?

Sure. Here is an "OrderedComparator" that compares elements according to a predefined order:

class OrderedComparator implements Comparator<String> {

    List<String> predefinedOrder;

    public OrderedComparator(String[] predefinedOrder) {
        this.predefinedOrder = Arrays.asList(predefinedOrder);
    }

    @Override
    public int compare(String o1, String o2) {
        return predefinedOrder.indexOf(o1) - predefinedOrder.indexOf(o2);
    }

}

And here is some test code. (I used a List instead of a Set since it 1) seem more natural when talking about the order of the elements and 2) better illustrate what happens with duplicate elements upon sorting using this comparator.)

class Test {

    public static void main(String[] args) {

        // Order (could be read from config file)
        String[] order = { "lorem", "ipsum", "dolor", "sit" };


        List<String> someList = new ArrayList<String>();

        // Insert elements in random order.
        someList.add("sit");
        someList.add("ipsum");
        someList.add("sit");
        someList.add("lorem");
        someList.add("dolor");
        someList.add("lorem");
        someList.add("ipsum");
        someList.add("lorem");


        System.out.println(someList);

        Collections.sort(someList, new OrderedComparator(order));

        System.out.println(someList);
    }

}

Output:

[sit, ipsum, sit, lorem, dolor, lorem, ipsum, lorem]
[lorem, lorem, lorem, ipsum, ipsum, dolor, sit, sit]

Java Comparable and Comparator interface examples, . a positive integer, if the first argument is greater than the second. Comparator Interface in Java with Examples. Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following function compare obj1 with obj2.

Take a look at TreeSet (http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html). You can provide a custom Comparator in a constructor. This Comparator will take into account your config. file . The logic of the comparator will not be pretty though since you want arbitrary order. You will most probably end up enumerating all possible comparisons.

Java Comparator Example for Custom Sorting , Comparator ), which will receive the SortingFieldsOrderBean as a parameter and will perform a comparison based on the order of fields passed  Returns a lexicographic-order comparator with another comparator. If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order. The returned comparator is serializable if the specified comparator is also serializable.

A set stores unordered elements. If you want to compare and sort, you should probably go with a list. Here's a quick snippet for you:

List<X> sorted = new ArrayList<X>(myset);
Collections.sort(sorted, new Comparator<X>() {
    public int compare(X o1, X o2) {
        if (/* o1 < o2 */) {
            return -1;
        } else if (/* o1 > o2 */) {
            return 1;
        } else {
            return 0;
        }
    }
});

Now you've got sorted, which has all the same elements of myset, which was unordered by virtue of being a set.

You can also look at TreeSet, which orders its elements, but it's generally not a good idea to rely on a set being ordered.

How to sort an ArrayList in Descending Order in Java, We used the reversed function on the Comparator in order to invert default natural order; that is, from lowest to highest. Comparator. Let's say the specific comparator I need to add sorts cars based for example on how far they are from the client. So it could be something like this (details are not important really, only the fact that it needs an additional parameter):

Use Guava's com.google.common.collect.Ordering:

Ordering.explicit(second_one, third_one, first_one);

The ComparatorFactory will search for several properties based on that In this way it is both fully configurable as well as transparent in your  The Comparator interface defines two methods: compare ( ) and equals ( ). The compare ( ) method, shown here, compares two elements for order − The compare Method. int compare (Object obj1, Object obj2) obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is

The method must ensure that the comparison is consistent. may want to sort the objects in a collection based on a value other than the natural ordering. You can also implement more complicated comparators that are configurable. The sort () method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

Ortiz J, Andrews D (2010) A configurable high-throughput linear sorter system. Pedroni VA (2004) Compact Hamming-comparator-based rank order filter for  Implement the java.util.Comparator interface at the enum-level in the SortingField. This will make all of the enum members abstract, and you need to implement a compare method of the interface at

For example, to sort a collection of String based on the length and then case-​insensitive natural ordering, the comparator can be composed using following code, Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java.util package and contains 2 methods compare (Object obj1,Object obj2) and equals (Object element). It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

Comments
  • I don't see what ordering this is. Can you elaborate on what you mean by the ordering?
  • @templatetypedef there is no logical explanation for this sorting flow, thats why I'd like to create comparator which uses some kind of template so it knows how to sort.
  • If it has an order, it is not a Set but a List. And you can use Comparators on Lists as you wish.
  • I guess I don't understand your question, then. What does sorted order mean for these objects? The sorted ordering you gave above doesn't look sorted at all.
  • @Bombe, which List takes a Comparator? Quite the opposite, if you need to provide a Comparator, use a TreeSet which is a Set.
  • I'd suggest changing the List to a Map from elements to their positions for efficiency reasons, but this is exactly what I was about to write. :-)
  • the OP wanted a Set not a List
  • I motivated why I chose a List instead of a Set in my answer.
  • can you give an example please, I don't know what you mean.
  • So your text file has a row for every pair, let's say the values are ABCD, and lets say that the order is A > B > C > D A B A C A D B C B D C D every line means that the first value is greater then the second value. You will read the file into your comparator and create a table which you will consult every time you need to do compare(). For example you can have a hashmap with keys like "AB", "BD" end so on and values -1 or 1 to indicate if the first part of the key is less then the second. wish I knew how to add line breaks here
  • But for a small set of values, aioobe's solution is much better, You can still use the comparator he provided in a tree set
  • >> generally not a good idea to rely on a set being ordered. why do you say that?
  • Because it's a set, not a list. Maybe it's just my math background, but I don't like it.