简体   繁体   中英

Sorting values in a tree map with string and list bean as parameters

Continuation from my previous question posted Sorting a map in java

I am trying out a solution to sort a tree map based on its values

Let me declare the Map

Map<String, List<Bean>> sortedBeanMap =new TreeMap<String,List<Bean>>();

i have created a separate comparator method to compare the values .

 public class MapSort {
    public static Map sortByValue(Map unsortedMap){

    Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
    sortedMap.putAll(unsortedMap);
    return sortedMap;
  }
  public static Map sortByKey(Map unsortedMap){
    Map sortedMap = new TreeMap();
    sortedMap.putAll(unsortedMap);
    return sortedMap;
  }
}

ValueComparator class

 public class ValueComparator implements Comparator {
  Map map;

  public ValueComparator(Map map){
    this.map = map;
  }
  public int compare(Object keyA, Object keyB){

    Comparable valueA = (Comparable) map.get(keyA);
    Comparable valueB = (Comparable) map.get(keyB);

    System.out.println(valueA +" - "+valueB);

    return valueA.compareTo(valueB);

  }
}

I knew the values should be of type string for the comparable to Work.But in my case , it will be a bean list.So how to get the comparator to work for my case ?

i am stuck in this for a while ..Any suggestions and ideas would be great .

Thanks guys in advance...

Since this is homework full code won't be supplied.

You are on the right track. Do create a class for your objects and implement the required methods for Comparable. You can decide what the "order" should be for two of your objects that have a list of beans: should on be smaller than another because the number of list elements are less; because the individual list elements have names that are "smaller"; or another well-defined ordering?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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