0

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;
              } 
          });
funk
  • 500
  • 5
  • 15
  • Not sure what you mean. Do you want to sort by id? Then you maybe should write a Comparable for a Collections.sort method. – Hasan Tuncay Nov 18 '13 at 08:21

3 Answers3

1

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);
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • And one more example http://stackoverflow.com/questions/12947088/java-treemap-comparator. – mvb13 Nov 18 '13 at 08:23
  • The TreeMap comparator sorts its keys, so unless the first element of each value array is also the key, I don't *think* this accomplishes what the OP wants (although I'm not quite clear what the OP wants). – Jason C Nov 18 '13 at 08:23
  • 1
    @JasonC: Yes I agree that `TreeMap isn't sorted on values.` I merely pointed a way to get custom sort in TreeMap and I am also not clear what exactly OP needs. – anubhava Nov 18 '13 at 08:25
  • i tried to use this but it does not work: SortedSet>> sortedset = new TreeSet>>( new Comparator>>() { public int compare(Entry> o1, Entry> o2) { /* return Integer.valueOf(o1.getValue()[1]).compareTo(Integer.valueOf(o2.getValue()[1]));*/ return 0; } }); – funk Nov 18 '13 at 09:17
  • @funk: Difficult to read code from comments, please post it in your question. – anubhava Nov 18 '13 at 09:18
0

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, e.g. 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, e.g.:

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.

Jason C
  • 38,729
  • 14
  • 126
  • 182
0

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());
            } 
         });
Prettygeek
  • 2,461
  • 3
  • 22
  • 44
  • You'd want to make id `final`, because if it is modified while it is in the map, it would break some invariants (key could no longer equal id, or sort order could change if it is in a set). Also, there is no `TreeMap` constructor that takes a `Comparator` -- the `Comparator` is for the key type only. – Jason C Nov 18 '13 at 08:34