1

I want to store key-value pairs in TreeMap and sort the entries based on the value of key as per the following logic:

  1. "type" (case insensitive) key should be at first.
  2. the key start with "metadata" (case insensitive) should be at last in ascending order
  3. rest of the keys(case insensitive) should be in middle in ascending order

I am using Java 8 version.

Program:

public class CustomeCamarator  {
    public static void main(String[] args) {
        CustomComparator comparator = new CustomComparator();
        Map<String,Object> empData=new TreeMap<>(comparator);
        empData.put("name","someName");
        empData.put("DOB","someDOB");
        empData.put("address","someAddress");
        empData.put("type","employee data");
        empData.put("ContactNo.","someContactNumber");
        empData.put("metadata.source","someMetaDataSource");
        empData.put("metadata.location","someMetaDataLocation");
        empData.put("metadata","someMetaData");
        System.out.println(empData);
        System.out.println(empData.containsKey("metadata"));//should be true but showing false
    }
}
class CustomComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        String str1 = o1.toLowerCase();
        String str2 = o2.toLowerCase();
        if(str1.equalsIgnoreCase("type")) {
            return -1;
        }else if(!str1.contains("metadata") && !str2.contains("metadata")) {
            return str1.compareTo(str2);
        }else if(o1.contains("metadata") && !o2.contains("metadata")) {
            return 1;
        }else if(!o1.contains("metadata") && o2.contains("metadata")) {
            return -1;
        }else {
            return 1;
        }
    }
}





**Expected Output like this:**
type: someType
address: someAddress
ContactNo: someContactNumber
DOB: someDOB
name: someName
metadata: someMetaData
metadata.location: someMetaDataLocation
metadata.source: someMetaDataSource

4 Answers 4

0

I think the following covers your cases

public class CustomComparator implements Comparator<String> {
  @Override public int compare(String left, String right) {
    left = left.toLowerCase();
    right = right.toLowerCase();
    final int LEFT = -1;
    final int RIGHT = 1;
    // exact match!
    if (left.equals(right)) return 0;
    // not identical, so consider 'type' match
    if ("type".equals(left)) return LEFT;
    if ("type".equals(right)) return RIGHT;
    // at this point we know neither matches 'type' so lets check for 'metadata' prefix
    if (left.startsWith("metadata")) {
      // if both start with metadata use natural ordering
      if (right.startsWith("metadata")) return left.compareTo(right);
      // only left starts with 'metadata' so right comes first
      else return RIGHT;
    }
    // only right starts with 'metadata' so left comes first
    if (right.startsWith("metadata")) return LEFT;
    // at this point we know they are not equal but neither contains 'text' nor starts with 'metadata' so use natural ordering
    return left.compareTo(right);
  }
}
2
  • 1
    The first lines of your compare method, final left = left.toLowerCase(); final right = right.toLowerCase(); are not valid syntax. For a variable declaration, they would need a type, but there are already variables with that name. For an assignment, the final modifier is inappropriate. Besides that, potentially creating new strings with lowercase versions, for the sake of a case insensitive comparison that might already stop at the first character, is very inefficient and not even correct for all characters and locales.
    – Holger
    Oct 5, 2020 at 15:19
  • 1
    You can implement the same logic as simple as Comparator<String> comparator = Comparator .comparing((String s) -> !"type".equalsIgnoreCase(s)) .thenComparing(s -> s.regionMatches(true, 0, "metadata", 0, 8)) .thenComparing(String.CASE_INSENSITIVE_ORDER); which is not only simpler but avoids creating new strings during the comparison.
    – Holger
    Oct 5, 2020 at 15:20
0

I used a Decision Table as follows

type  metadata.*  others
2     1           0

Key 1    Key 2    Result    Action
  0        0        0       String.compare
  0        1        1       return -1
  0        2        2       return 1
  1        0        3       return 1
  1        1        4       String.compare
  1        2        5       return 1
  2        0        6       return -1
  2        1        7       return -1
  2        2        8       return 0

Key 1 and Key 2 are the parameters to method compare() of interface Comparator. Each key can have one of three values:

  1. type
  2. [starts with] metadata
  3. none of the above

Here is the implementation:

Comparator<String> comparator = (k1, k2) -> {
    Objects.requireNonNull(k1);
    Objects.requireNonNull(k2);
    int k1Val;
    int k2Val;
    if (k1.equalsIgnoreCase("type")) {
        k1Val = 2;
    }
    else if (k1.matches("(?i)^metadata.*$")) {
        k1Val = 1;
    }
    else {
        k1Val = 0;
    }
    if (k2.equalsIgnoreCase("type")) {
        k2Val = 2;
    }
    else if (k2.matches("(?i)^metadata.*$")) {
        k2Val = 1;
    }
    else {
        k2Val = 0;
    }
    int retVal;
    int index = k1Val * 3 + k2Val;
    switch (index) {
        case 0:
        case 4:
            retVal = k1.compareToIgnoreCase(k2);
            break;
        case 1:
        case 6:
        case 7:
            retVal = -1;
            break;
        case 2:
        case 3:
        case 5:
            retVal = 1;
            break;
        case 8:
            retVal = 0;
            break;
        default:
            throw new RuntimeException("Unhandled: " + index);
    }
    return retVal;
};
Map<String, Object> empData = new TreeMap<>(comparator);
empData.put("name","someName");
empData.put("address","someAddress");
empData.put("type","employee data");
empData.put("ContactNo.","someContactNumber");
empData.put("Metadata.source","someMetaDataSource");
empData.put("metadata.location","someMetaDataLocation");
empData.put("metadata","someMetaData");
System.out.println(empData);

Output from running above code.

{type=employee data, address=someAddress, ContactNo.=someContactNumber, name=someName, metadata=someMetaData, metadata.location=someMetaDataLocation, Metadata.source=someMetaDataSource}
0

You should pass a comparator that implements that logic to the TreeMap constructor:

Map<String, Integer> order = Map.of(
    "type", Integer.MIN_VALUE, 
    "metadata", Integer.MAX_VALUE);

Map<String, Object> map = new TreeMap<>(
    Comparator.comparing(a -> order.getOrDefault(
        a.toLowerCase().startsWith("metadata") ?
            "metadata" :
            a.toLowerCase(), 
        0))
    .thenComparing(Comparator.naturalOrder()));

I think this should do it. The idea is to use a map to first compare by some Integer value. The value corresponding to type is Integer's min value, so that it always comes first. The value for metadata is Integer's max value, so that it always comes last. Before searching in the map, we first check if the string starts with metadata. It it does, we just change it to metadata, to obtain the Integer value from the map. If there is no entry in the map, we return 0. It there's a tie, we use String's natural order.


EDIT: If you are on Java8 and cannot use Map.of, consider using a traditional HashMap instead:

Map<String, Integer> order = new HashMap<>();
order.put("type", Integer.MIN_VALUE);
order.put("metadata", Integer.MAX_VALUE);
2
  • Thank You @fps for your response but we are using JAVA 8 and Map.of is introduced in JAVA 9. Oct 1, 2020 at 14:28
  • @VinayakKanade Added a java8 compatible version
    – fps
    Oct 1, 2020 at 15:11
-1

TreeMap supports a custom Comparator in its constructor. Just implement the Comparator interface and pass it to the constructor.

3
  • I think that @VinayakKanade is asking for the actual implementation. The question title states: How to write custom comparator in java
    – Abra
    Oct 1, 2020 at 13:34
  • @Abra He's not showing any attempt to use a Comparator in his code.
    – m0skit0
    Oct 1, 2020 at 13:58
  • Added my attempt Oct 1, 2020 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.