I have created a Hash map where I need to store two different values corresponding to one key. Using
final Map<String, List<Double>> map = new HashMap<String, List<Double>>();
final List<Double> valSetOne = new ArrayList<Double>();
for(int i=0;i<100;i++)
{
valSetOne.add(movies.getPrice());
valSetOne.add(movies.getSeat());
map.put(movies.getId, valSetOne);
}
System.out.println(map);
On printing the value of map I'm getting output something like this{1235567=[1100.00,100], 1256689=[1300.00,100]}
Now I want to sort this hash map in descending order on the basis of price ie key and values of 1300.00 should come before 1100.00.
Considering that you are building your HashMap<String, List<Double>>
correctly with each entry having String
parameter representing your movieId
as key
and a List<Double>
parameter as value
which contains movies.getPrice()
as it's first entry and movies.getSeat()
as it's second entry, you can create a TreeMap<String, List<Double>>
with a Comparator
and add all the entries of your old map
to it in order to get a sorted version of your old map
based on the movie price . TreeMap
construction can be done like this:
Java 8 way:
TreeMap<String, List<Double>> priceSortedMap = new TreeMap<>((o1, o2) ->{
//get first entry (movie price) of list and compare.
if(map.get(o1).get(0) <= map.get(o2).get(0)){
return 1;
}
return -1;
});
// put all entries from old map to new
priceSortedMap.putAll(map);
Here o1
and o2
are the String
keys.
Java 7 way:
TreeMap<String, List<Double>> priceSortedMap = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//get first entry (movie price) of list and compare.
if(map.get(o1).get(0) <= map.get(o2).get(0)){
return 1;
}
return -1;
}
});
// put all entries from old map to new
priceSortedMap.putAll(map);
I hope this is what you were trying to achieve.
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.