简体   繁体   中英

Java sort by first index of the array list in a map

I know that i can sort a Map using TreeMap but i don't know how to sort by value where the id is the first index of the ArrayList.

Here is the code:

public void sort()
{
  Map<String, ArrayList<String>> m = new TreeMap<String,ArrayList<String>>();
  String[] name = new String[]{"first name", "second name", "third name"};
  String[] description = new String[]{"first description", "second description", "third description"};
  String[] id = new String[]{"1", "2", "3"};
  m.put(name[0], new ArrayList<String>(Arrays.asList(new String[]{description[0], id[0]})));
  m.put(name[1], new ArrayList<String>(Arrays.asList(new String[]{description[1], id[1]})));
  m.put(name[2], new ArrayList<String>(Arrays.asList(new String[]{description[2], id[2]})));
}

I tried this to sort the Map:

SortedSet<Map.Entry<String, ArrayList<String>>> sortedset = new TreeSet<Map.Entry<String, ArrayList<String>>>(
          new Comparator<Map.Entry<String, ArrayList<String>>>() 
          {
              public int compare(Entry<String, ArrayList<String>> o1, Entry<String, ArrayList<String>> o2)
              {
                // return Integer.valueOf(o1.getValue()[1]).compareTo(Integer.valueOf(o2.getValue()[1]));
                return 0;
              } 
          });

TreeMap accepts a custom comparator also. You need to create a custom Comparator and pass it in TreeMap as:

// assuming you create mycomparator
Map<String, ArrayList<String>> m = new TreeMap<String,ArrayList<String>>(mycomparator);

Your question is slightly confusing. A TreeMap is naturally "sorted" by the keys (well, it appears sorted when you iterate through it).

If you want to sort by the first item in the value, then you either need to use the first item in the value as the key, or copy all of the values into a sortable collection, eg an ArrayList , then sort with a custom Comparator that compares the first element of each array.

You could also use a TreeSet with a custom Comparator that compares the first item in each array. Then insert all your arrays into the TreeSet .

You may also want to consider creating a custom class with your data as fields, instead of parallel arrays. Then that class can implement Comparable , and you can insert your collection of them into a TreeSet as-is, eg:

public class Item implements Comparable<Item> {

    private final String id;
    private String name;
    private String description;

    public Item (String id) {
        this.id = id; 
    }

    @Override public int compareTo (Item item) {
        // not shown for simplicity: check item, id, item.id for null.
        return id.compareTo(item.id);
    }

}

... {
    TreeSet<Item> items = new TreeSet<Item>();
    items.add(new Item(...));
    items.add(new Item(...));
    items.add(new Item(...));
    // items will be naturally sorted by item id.
}

In the above example, you'd want to make id be final so that the id can't be changed while the Item is in the set, thus breaking the set.

You should implement simple class to hold informations and then use a collection, it will be easy to sort it and manage a values. Then use your Map object, use ID as a key and Map will be autosorted and you can use custom comparator to sort Map by other values.

Example class

public class Obj{
    final int ID;
    String desctiption, name;
            public Obj(int _ID){
                    ID=_ID;
            }

    /**
     * @return the iD
     */
    public int getID() {
        return ID;
    }
    /**
     * @param iD the iD to set
     */
    public void setID(int iD) {
        ID = iD;
    }
    /**
     * @return the desctiption
     */
    public String getDesctiption() {
        return desctiption;
    }
    /**
     * @param desctiption the desctiption to set
     */
    public void setDesctiption(String desctiption) {
        this.desctiption = desctiption;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }



}

if you want to use custom comparator your class should implement Comparable interface, then use something like this

   SortedSet<Map.Entry<int, Obj>> sortedset = new TreeSet<Map.Entry<int, Obj>>(
            new Comparator<Map.Entry<int, Obj>>() 
         {

             public int compare(Entry<int, Obj> o1, Entry<int, Obj> o2)
             {
                 return o1.getValue().compareTo(o2.getValue());
            } 
         });

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