【问题标题】:how to sort hash map with keys as string and values as object如何使用键作为字符串和值作为对象对哈希映射进行排序
【发布时间】:2015-12-12 20:02:51
【问题描述】:

我有一个以字符串为键、对象为值的 HashMap。如何按 Objects 中的 FirstName 字段对 HashMap 进行排序。这是实际的 HashMap 表示 HashMap<String, AttendanceData> attendanceDataMap=new HashMap<String, AttendanceData>();

HashMap 的键是 AttendanceData 对象的 id

AttendanceData 类的样子

public class AttendanceData{

private TakenBy takenBy;

private String id;

private String user_name;

private String first_name;

private String description;

private String last_name;

public AttendanceData(String id, String firstName, String lastName, String takenBy, String description, String userName)
{
    this.id=id;
    this.first_name=firstName;
    this.last_name=lastName;
    this.takenBy=takenBy;
    this.description=description;
    this.user_name=userName;
}

【问题讨论】:

  • 比较器在这里会有所帮助

标签: android collections hashmap


【解决方案1】:
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

【讨论】:

  • 实际上我想按 first_name 字段对 HashMap 进行排序,该字段将位于 HashMap 包含的 AttendanceData 对象内
  • 你应该使用 Comperator。可能这个问题会对你有所帮助。 stackoverflow.com/questions/1206073/…
【解决方案2】:

我认为比较器可能会有所帮助,请在下面粘贴示例,请注意这不是具体答案,您必须根据需要进行修改:

public class HMapSortingByvalues {
  public static void main(String[] args) {
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();
      hmap.put(5, "A");
      hmap.put(11, "C");
      hmap.put(4, "Z");
      hmap.put(77, "Y");
      hmap.put(9, "P");
      hmap.put(66, "Q");
      hmap.put(0, "R");
      System.out.println("Before Sorting:");
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
           Map.Entry me = (Map.Entry)iterator.next();
           System.out.print(me.getKey() + ": ");
           System.out.println(me.getValue());
      }
      Map<Integer, String> map = sortByValues(hmap); 
      System.out.println("After Sorting:");
      Set set2 = map.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
           Map.Entry me2 = (Map.Entry)iterator2.next();
           System.out.print(me2.getKey() + ": ");
           System.out.println(me2.getValue());
      }
  }

  private static HashMap sortByValues(HashMap map) { 
       List list = new LinkedList(map.entrySet());
       // Defined Custom Comparator here
       Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());
            }
       });

       // Here I am copying the sorted list in HashMap
       // using LinkedHashMap to preserve the insertion order
       HashMap sortedHashMap = new LinkedHashMap();
       for (Iterator it = list.iterator(); it.hasNext();) {
              Map.Entry entry = (Map.Entry) it.next();
              sortedHashMap.put(entry.getKey(), entry.getValue());
       } 
       return sortedHashMap;
  }
}

【讨论】:

    【解决方案3】:

    HashMap 不支持排序。但当然,您可以对值进行排序。实施 Comparable 例如:

    List list = new ArrayList(Map.entrySet());
    Collections.sort(list, new Comparator() {
      @Override
      public int compare(Entry e1, Entry e2) {
        return e1.getValue().compareTo(e2.getValue());
      }
    });
    

    此外,您还可以使用 SortedMap(例如 TreeMap)。但它只支持按键排序。虽然你可以尝试使用这个比较器:

    class ValueComparator implements Comparator {
    
      Map base;
      public ValueComparator(Map base) {
          this.base = base;
      }
    
      public int compare(Object a, Object b) {
    
        if((Double)base.get(a) < (Double)base.get(b)) {
          return 1;
        } else if((Double)base.get(a) == (Double)base.get(b)) {
          return 0;
        } else {
          return -1;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 2015-03-16
      • 2021-09-06
      • 2015-09-21
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多