Java中查找Map<Integer, String>中小于指定值的最大键
在Java中,可以使用数组和循环来查找一个Map<Integer, String>中小于指定键值的最大键。首先,将Map中的键值存储在一个数组中。然后,遍历数组,找到小于指定值的最大的键。
以下是一个使用Java代码实现的示例:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "value1");
map.put(10, "value10");
map.put(14, "value14");
map.put(18, "value18");
map.put(22, "value22");
map.put(26, "value26");
map.put(30, "value30");
map.put(35, "value35");
map.put(39, "value39");
int[] keys = {1, 10, 14, 18, 22, 26, 30, 35, 39};
int target = 11;
int max = Integer.MIN_VALUE;
for (int key : keys) {
if (key < target && key > max) {
max = key;
}
}
System.out.println("最大值为:" + max);
}
}
在这个示例中,我们使用HashMap来存储key和value的对应关系。然后,我们将key的值存储在一个数组中,并使用一个变量max来记录小于11的最大值。接下来,我们遍历数组,如果当前的key值小于目标值11并且大于max,则更新max的值。最后,打印出小于11的最大值。
输出结果为:最大值为:10
原文地址: https://www.cveoy.top/t/topic/qewv 著作权归作者所有。请勿转载和采集!