Sorting Map using Comparator

北城余情 提交于 2019-12-06 05:01:09

Here is some simple code that should to the task.

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class FixedOrderComparator implements Comparator<String> {

  private final Map<String, Integer> index = new HashMap<>();

  public FixedOrderComparator(String elements) {
    String[] split = elements.split(",");
    for (int i = 0; i < split.length; i++) {
      index.put(split[i], i);
    }
  }

  @Override
  public int compare(String left, String right) {
    Integer rankLeft = index.get(left);
    Integer rankRight = index.get(right);
    if (rankLeft != null && rankRight != null) {
      return rankLeft.compareTo(rankRight);
    }
    if (rankLeft == null && rankRight == null) {
      return left.compareTo(right);
    }
    return Boolean.compare(rankLeft == null, rankRight == null);
  }

}

You have to correct your logic used in the comparator.

  final String sequence="People,Object,Environment,Message,Service";
  System.out.println(sequence.indexOf("People"));  // 0
  System.out.println(sequence.indexOf("Object"));  // 7
  System.out.println(sequence.indexOf("Message"));  // 26
  System.out.println(sequence.indexOf("Environment")); // 14

.indexOf(key1) returns the index of the first character of the String and not the String.

 int returned = sequence.indexOf(key1) - sequence.indexOf(key2);
 if(returned < 0){ 
    // then it is sorted; 
    return 1;
 }
 else{ return -1; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!