Java8中遍历Map、Map转List、List转Map
1.遍历Map
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
// Map.keySet遍历
for (Integer k : map.keySet()) {
System.out.println(k + " ==> " + map.get(k));
}
map.keySet().forEach(k -> System.out.println(k + " ==> " + map.get(k)));
// Map.entrySet遍历
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
map.entrySet().forEach(entry -> System.out.println(entry.getKey() + " ==> " + entry.getValue()));
// 迭代器遍历
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
map.entrySet().iterator()
.forEachRemaining(entry -> System.out.println(entry.getKey() + " ==> " + entry.getValue()));
// 遍历values
for (String v : map.values()) {
System.out.println(v);
}
map.values().forEach(System.out::println);
// Lambda
map.forEach((k, v) -> System.out.println(k + " ==> " + v));
2.集合转Map
List<KeyValue> list = new ArrayList<>();
list.add(new KeyValue(1, "A"));
list.add(new KeyValue(2, "B"));
list.add(new KeyValue(3, "C"));
// 遍历
Map<Integer, String> keyValueMap = new HashMap<>();
for (KeyValue keyValue : list) {
keyValueMap.put(keyValue.getKey(), keyValue.getValue());
}
keyValueMap.forEach((k, v) -> System.out.println(k + " ==> " + v));
// Stream流
Map<Integer, String> map = list.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue));
map.forEach((k, v) -> System.out.println(k + " ==> " + v));
3.Map转List
class KeyValue {
private Integer key;
private String value;
@Override
public String toString() {
return key + "{}" + value;
}
}
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
// key 转 List
List<Integer> keyList = new ArrayList<>(map.keySet());
List<Integer> keyList2 = map.keySet().stream().collect(Collectors.toList());
keyList.forEach(System.out::println);
keyList2.forEach(System.out::println);
// value 转 List
List<String> valueList = new ArrayList<>(map.values());
List<String> valueList2 = map.values().stream().collect(Collectors.toList());
valueList.forEach(System.out::println);
valueList2.forEach(System.out::println);
// Iterator转List
List<KeyValue> keyValueList = new ArrayList<>();
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()) {
Integer k = (Integer) it.next();
keyValueList.add(new KeyValue(k, map.get(k)));
}
keyValueList.forEach(System.out::println);
// Java8 Stream
List<KeyValue> list = map.entrySet().stream().map(c -> new KeyValue(c.getKey(), c.getValue()))
.collect(Collectors.toList());
list.forEach(System.out::println);
本文作者:chillymint
本文链接:https://www.cnblogs.com/chillymint/p/17713884.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步