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);
标签:Map,map,List,System,println,Java8,out
From: https://www.cnblogs.com/chillymint/p/17713884.html