返回嵌套哈希图中具有最低值的键
Returning they key with lowest value in a nested hashmap
我有这个哈希图:
{count : {req : deadline}, count : {req : deadline}, count : {req : deadline}, count : {req : deadline}}
如果我把它放在值中是:
{0 : {req : 5}, 1 : {req : 3}, 2 : {req : 1}, 3 : {req : 3}}
我想比较所有 deadline
值,看看哪个具有最低值,return count
具有 deadline
.
所以在这种情况下最低的“截止日期”= 1,对应的“计数”= 2。
您可以使用 <Integer, DataHolder>
类型的 HashMap
,然后根据值对地图进行排序并访问第一个元素。
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());
}
}
我有这个哈希图:
{count : {req : deadline}, count : {req : deadline}, count : {req : deadline}, count : {req : deadline}}
如果我把它放在值中是:
{0 : {req : 5}, 1 : {req : 3}, 2 : {req : 1}, 3 : {req : 3}}
我想比较所有 deadline
值,看看哪个具有最低值,return count
具有 deadline
.
所以在这种情况下最低的“截止日期”= 1,对应的“计数”= 2。
您可以使用 <Integer, DataHolder>
类型的 HashMap
,然后根据值对地图进行排序并访问第一个元素。
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());
}
}