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;
              } 
          });
1
  • Not sure what you mean. Do you want to sort by id? Then you maybe should write a Comparable for a Collections.sort method. Commented Nov 18, 2013 at 8:21

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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).
@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.
i tried to use this but it does not work: 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: Difficult to read code from comments, please post it in your question.
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());
            } 
         });

1 Comment

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<Entry> -- the Comparator is for the key type only.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.