开发中遇到了Map对应的key和value需要互换的需求。以及按key进行默认排序重装,还有就是针对于key和value组装url连接。
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("c", "c1");
map.put("b", "b1");
map.put("a", "a1");
map.put("1", "1");
System.out.println(map);
//将key和value互换
map = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
System.out.println(map);
//按key值进行Ascii排序 1.先排序 2.创建一个链表的map进行值的存储
map = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(map);
//按key值进行Ascii排序后,拼接成url路径的形式
String collect = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(e ->e.getKey()+"="+e.getValue()).collect(Collectors.joining("&"));
System.out.println(collect);
}
}
运行结果