简体   繁体   English

基于hashMap值排序HashMaps列表[不是键]

[英]Sort List of HashMaps based on hashMap values [not keys]

Here is what I have- 这是我的 -

How I can include multiple keys and their values in comparison? 我如何在比较中包含多个键及其值? Right now I am only using employeeId but I wanted to include departmentId and other in my comparison for sorting... 现在我只使用employeeId,但我想在我的比较中包括departmentId和其他用于排序......

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class Tester {

    boolean flag = false ;


    public static void main(String args[]) {
        Tester tester = new Tester() ;
        tester.printValues() ;
    }

    public void printValues ()
    {

        List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>() ;
        HashMap<String,Object> map = new HashMap<String,Object>();


        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(1234)) ;
        map.put("departmentId", new Integer(110)) ;
        map.put("someFlag", "B") ;
        map.put("eventTypeId", new Integer(11)) ;
        map.put("startDate", new Date() ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);


        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(456)) ;
        map.put("departmentId", new Integer(100)) ;
        map.put("someFlag", "B") ;
        map.put("eventTypeId", new Integer(11)) ;
        map.put("startDate", new Date() ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);


        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(1234)) ;
        map.put("departmentId", new Integer(10)) ;
        map.put("someFlag", "B") ;
        map.put("eventTypeId", new Integer(17)) ;
        map.put("startDate", new Date() ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);

        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(1234)) ;
        map.put("departmentId", new Integer(99)) ;
        map.put("someFlag", "B") ;
        map.put("eventTypeId", new Integer(11)) ;
        map.put("startDate", new Date() ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);

        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(1234)) ;
        map.put("departmentId", new Integer(100)) ;
        map.put("someFlag", "B") ;
        map.put("eventTypeId", new Integer(11)) ;
        map.put("startDate", new Date() ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);



        map = new HashMap<String,Object>();
        map.put("employeeId", new Integer(567)) ;
        map.put("departmentId", new Integer(200)) ;
        map.put("someFlag", "P") ;
        map.put("eventTypeId", new Integer(12)) ;
        map.put("startDate", new Date()  ) ;
        map.put("endDate", new Date() ) ;
        list.add(map);

        Collections.sort ( list , new HashMapComparator2 () ) ;

        for( int i = 0 ; i < list.size() ; i ++ ) {
            System.out.println(list.get(i));    
        }

        System.out.println("======================================");    


        flag = true ; // desc
        Collections.sort ( list , new HashMapComparator2 () ) ;

        for( int i = 0 ; i < list.size() ; i ++ ) {
            System.out.println(list.get(i));    
        }

    }

    public class HashMapComparator2 implements Comparator
    {
        public int compare ( Object object1 , Object object2 )
        {
            if ( flag == false )
            {


                Integer obj1Value = ( Integer ) ( ( HashMap ) object1 ).get ( "employeeId" ) ;
                Integer obj2Value = ( Integer ) ( ( HashMap ) object2 ).get ( "employeeId" ) ;

                return obj1Value.compareTo ( obj2Value ) ;
            }
            else
            {
                Integer obj1Value = ( Integer ) ( ( HashMap ) object1 ).get ( "employeeId" ) ;
                Integer obj2Value = ( Integer ) ( ( HashMap ) object2 ).get ( "employeeId" ) ;

                return obj2Value.compareTo ( obj1Value ) ;
            }
        }
    }


}

First I would create a Class to store the data instead of using a List of HashMaps. 首先,我将创建一个类来存储数据,而不是使用List of HashMaps。 Then make that class implement the Comparable interface which allows you determine a finely-grained comparison algorithm. 然后使该类实现Comparable接口,该接口允许您确定细粒度的比较算​​法。

If you absolutely need to use a HashMap then I would create a class that extends HashMap AND implements Comparable. 如果你绝对需要使用HashMap,那么我将创建一个扩展HashMap并实现Comparable的类。 But I don't recommend that approach. 但我不建议采用这种方法。

public class Foo extends HashMap implements Comparable {
  private boolean ascending = true;

  public int compareTo(Object bar) {
    int result;
    if (bar == null || !(bar instanceof Foo)) {
      result = -1;
    }
    Foo _rhs = (Foo)bar;
    result = new CompareToBuilder().append(get("employeeId"),_rhs.get("employeeId"))
                 .append(get("departmentId"),_rhs.get("departmentId")).toComparison();

    return (ascending ? result : -result);
  }

  public void setAscending(boolean asc) {
    ascending = asc;
  }
}

No guarantees that this code will compile or return correct results. 不保证此代码将编译或返回正确的结果。 I really like the CompareToBuilder 我非常喜欢CompareToBuilder

The easiest is using the CompareToBuilder from commons-lang . 最简单的方法是使用commons-langCompareToBuilder Your example would look like this: 您的示例如下所示:

Map<String, Object> map1 = (Map<String, Object>) object1;
Map<String, Object> map2 = (Map<String, Object>) object2;
if ( flag == false ) {
    return new CompareToBuilder()
        .append(map1.get("employeeId"), map2.get("employeeId"))
        .append(map1.get("departmentId"), map2.get("departmentId"))
        .toComparison();
}
else {
    return new CompareToBuilder()
        .append(map2.get("employeeId"), map1.get("employeeId"))
        .append(map2.get("departmentId"), map1.get("departmentId"))
        .toComparison();
}

Or something like that. 或类似的东西。 Anyway, I would definitely recommend that you use Genrics in your comparators, as suggested by Daniil. 无论如何,我肯定会建议您在比较器中使用Genrics,如Daniil所建议的那样。

martinatime's answer is correct. martinatime的回答是正确的。 Create a class to store your data. 创建一个类来存储您的数据。 Then you put it into map that supports key sorting, such as TreeMap: 然后将其放入支持键排序的映射中,例如TreeMap:

new TreeMap<Integer, YouNewClass>(new Comparator<YourNewClass>() {

 public int compare(YourNewClass o1, YourNewClass o2) {
       implement the method here as per your logic.
 }

});

Enjoy: http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html 享受: http//java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM