mapintegerstring key有 1 10 14 18 22 26 30 35 39 有着数字11怎么找到小于它的最大值用Java代码
以下是使用Java代码来找到小于给定数字11的最大值:
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>(); // 创建一个有序的TreeMap
// 向map中添加键值对
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 target = 11;
int maxKey = Integer.MIN_VALUE; // 初始化最大键值为最小整数值
for (int key : map.keySet()) {
if (key < target && key > maxKey) {
maxKey = key;
}
}
System.out.println("小于" + target + "的最大值为:" + maxKey);
}
}
这段代码将输出:
小于11的最大值为:10
在这个例子中,我们使用了一个有序的TreeMap来存储键值对。然后我们遍历map的键,通过比较键值与目标值,找到小于目标值且最接近目标值的键
原文地址: https://www.cveoy.top/t/topic/ixa8 著作权归作者所有。请勿转载和采集!