0

How to fix this issue/error ( How to sort nested TreeMap in java) When i am trying to sort Map using item price it is not working because TreeMap sort in natural order according to key but i need to sort this by using inner map key. any one help me..

public class SortedTest {

private static Map<Integer, Map<Item, Integer>> tm = new TreeMap<>();

public static void main(String[] args) {
    Item item = new Item("beer", 1, 5.0);
    Item item1 = new Item("tofu", 2, 3.5);
    Item item2 = new Item("ic", 3, 3.2);
    Item item3 = new Item("mg", 4, 4.5);


    tm.put(item.getId(), new TreeMap<>());
    tm.get(item.getId()).put(item, 3);

    System.out.println(tm);

    tm.put(item1.getId(), new TreeMap<>());
    tm.get(item1.getId()).put(item1, 3);
    System.out.println(tm);

  } 
}
package trial;


public class Item implements Comparable<Item> {
private String name;
private Integer id;
private Double price;

// constructor, setter & getter

@Override
public int compareTo(Item o) {
    if (getPrice() > o.getPrice()) {
        return 1;
    }
    if (price < o.getPrice()) {
        return -1;
    }
    return 0;
}

@Override
public String toString() {
    return "Item{" +
            "name='" + name + '\'' +
            ", id=" + id +
            ", price=" + price +
            '}';
}
}
3
  • why are you using map of maps? Commented May 22, 2018 at 11:54
  • You are sorting each of the inner Maps by price. How would an ordering of the outer Map by price look like? Commented May 22, 2018 at 11:54
  • I am not able to figure out, if you can help me it would be nice of you,anyway thanks for your effort. Commented May 22, 2018 at 12:48

1 Answer 1

0

Actually you are trying to sort map by value, comparable method or comparator can do it with keys only.

Sign up to request clarification or add additional context in comments.

2 Comments

my requirement is like that i need to sort using inner map i.e. value of outer map, thanks for your efforts :)
Please,take a look at ValueComparator stackoverflow.com/questions/109383/…

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.