How to compare and sort nested Map in java based on Item price?

501 Views Asked by At

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 +
            '}';
}
}
1

There are 1 best solutions below

2
On

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