str="a:10,b:11,c:12,d:13" 如何找最大的那个,返回a或者d,j
要看看是以什么判断,是a,b,c,d来判断还是10,11,12,13判断。java可以先将字符串进行分割,str要保证是String类型。
String [] strArray = str.split(",");
for(int i = 0;i < strArray.length;i++){
String x = strArray[i];
String [] xArray = x.split(":");
//这样里面的a或10就可以取出来了,然后进行循环比较
}
public static void main(String[] args) {
String str="a:10,b:11,c:12,d:13";
//通过逗号先分割
String[] strs = str.split(",");
Map<String,Integer> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
//分割完后将每一个存到map里面
map.put(strs[i].split(":")[0],Integer.parseInt(strs[i].split(":")[1]));
}
//将map集合里面的值存放在list里面
List<Integer> list = new ArrayList<Integer>();
for (String string : map.keySet()) {
list.add(map.get(string));
}
//将list里面的值遍历到数组里面
int[] array = new int[strs.length];
for (int i = 0; i < list.size(); i++) {
array[i]=list.get(i);
}
//数组排序的方法 默认是升序
Arrays.sort(array);
for (String string : map.keySet()) {
if(map.get(string) == array[array.length-1]) {
System.out.println("数字最大的那个键是:"+string);
}
}
}
如下:
public static void compare() {
//字符串a:10,b:11,c:12,d:13
String str="a:10,b:11,c:12,d:13";
//转为数组a,10,b,11,c,12,d,13
String[] eles = str.split("[,:]");
//先取第一个键和值
String maxKey = eles[0];
int maxValue = Integer.parseInt(eles[1]);
//遍历数组元素,间隔2
for (int i=0; i<eles.length; i=i+2) {
//假如下一个值大,则替换最大值
if (maxValue < Integer.parseInt(eles[i+1])) {
maxValue = Integer.parseInt(eles[i+1]);
maxKey = eles[i];
}
}
//输出最大key及value
System.out.println(maxKey+"|"+maxValue);
}