Java中Map和List组合使用的例子

时间:2021-12-25 23:30:00

使用Java很方便的一条就是Java封装了很多方便使用的Map和List。

这是我在开发过程中遇到的问题,通过传入的字符串封装成List<Map<String, String>>格式,然后进行想要的操作,奉上代码!

/* 输入参数:
* [{"index":"SB001","value":"0.380658"},{"indexNo":"SB002","value":"19.801300"},
* {"index":"SB003","value":"1.479825"},{"indexNo":"SB004","value":"15.371400"},
* {"index":"SB005","value":"1.079054"}]
* 返回值:
* [{"index":"SB001","value":"0.380658","chineseParam":"指标一"},{"indexNo":"SB002","value":"19.801300","chineseParam":"指标二"},
* {"index":"SB003","value":"1.479825","chineseParam":"指标三"},{"indexNo":"SB004","value":"15.371400","chineseParam":"指标四"},
* {"index":"SB005","value":"1.079054","chineseParam":"指标五"}]
*/
public static List<Map<String, String>> addKeyAndValueInMap(List<Map<String, String>> list) {

Map<String, String> keyValue =new HashMap<String,String>();
keyValue.put("SB001", "指标一");
keyValue.put("SB002", "指标二");
keyValue.put("SB003", "指标三");
keyValue.put("SB004", "指标四");
keyValue.put("SB005", "指标五");
keyValue.put("SB006", "指标六");
keyValue.put("SB007", "指标七");

for(Map<String, String> map : list){
String key = map.get("index");
if(keyValue.containsKey(key)){
map.put("chineseParam", keyValue.get(key));
}
}

return list;
}
/* 输入参数:list1
* [{"index":"SB001","value":"0.3"},{"indexNo":"SB002","value":"19.0"},
* {"index":"SB003","value":"1.4"},{"indexNo":"SB004","value":"15"},
* {"index":"SB005","value":"1.0"}]
* 输入参数:list2
* [{"index":"SB001","value":"0.4"},{"indexNo":"SB002","value":"19.1"},
* {"index":"SB003","value":"1.5"},{"indexNo":"SB004","value":"12"},
* {"index":"SB005","value":"1.0"}]
* 返回值:
* ["SB001":"1","SB002":"1",
* "SB003":"1","SB004":"-1",
* "SB005":"1"]
*/
public static Map<String, String> compareList(List<Map<String, String>> list1,List<Map<String, String>> list2){

Map<String , String> map1 = new HashMap<String , String>() ;
Map<String , String> map2 = new HashMap<String , String>() ;
for(Map<String , String> a : list1){
map1.put( a.get("index") , a.get("value")) ;
}
for(Map<String , String> b : list2){
map2.put( b.get("index") , b.get("value")) ;
}

Map<String , String> map3 = new HashMap<String , String>() ;
for(Map.Entry<String, String> a : map1.entrySet()){
String key = a.getKey() ;
String value = a.getValue() ;
if(map2.containsKey(key)){
map3.put(key , value.compareTo(map2.get(key)) < 0 ? "-1" : "1") ;
}
}
return map3;
}