I have this hashmap:
{count : {req : deadline}, count : {req : deadline}, count : {req : deadline}, count : {req : deadline}}
If I put it in values is:
{0 : {req : 5}, 1 : {req : 3}, 2 : {req : 1}, 3 : {req : 3}}
I want to compare all the deadline values and see which one has the lowest value and return the count that has that deadline.
So in this case the lowest “deadline” = 1, which corresponds to the “count” = 2.
Advertisement
Answer
You can use HashMap of type <Integer, DataHolder> and then sort the map based on values and access the first element.
See below code
public class Sample {
static class Data {
String key;
Integer value;
public Data(String key, Integer value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "Data{" +
"key='" + key + ''' +
", value=" + value +
'}';
}
}
public static void main(String[] args) throws InterruptedException, IOException {
Map<Integer, Data> map = new HashMap<>();
map.put(0, new Data("req", 5));
map.put(1, new Data("req", 3));
map.put(2, new Data("req", 1));
map.put(3, new Data("req", 3));
List<Map.Entry<Integer, Data>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, Comparator.comparing(o -> o.getValue().value));
System.out.println(list.stream().findFirst().get().getKey());
}
}