遍历Map
Map 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 entry : map.entrySet()) {
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
map.entrySet().forEach(entry -> System.out.println(entry.getKey() + " ==> " + entry.getValue()));
// Iterator遍历
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry 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);
// Java8 Lambda
map.forEach((k, v) -> System.out.println(k + " ==> " + v));
Map转List
@Data
@NoArgsConstructor
@AllArgsConstructor
class KeyValue {
private Integer key;
private String value;
@Override
public String toString() {
return key + " ==> " + value;
}
}
Map map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
// key 转 List
List keyList = new ArrayList<>(map.keySet());
List keyList2 = map.keySet().stream().collect(Collectors.toList());
keyList.forEach(System.out::println);
keyList2.forEach(System.out::println);
// value 转 List
List valueList = new ArrayList<>(map.values());
List valueList2 = map.values().stream().collect(Collectors.toList());
valueList.forEach(System.out::println);
valueList2.forEach(System.out::println);
// Iterator转List
List keyValueList = new ArrayList<>();
Iterator 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 list = map.entrySet().stream().map(c -> new KeyValue(c.getKey(), c.getValue()))
.collect(Collectors.toList());
list.forEach(System.out::println);
List转Map
List list = new ArrayList<>();
list.add(new KeyValue(1, "a"));
list.add(new KeyValue(2, "b"));
list.add(new KeyValue(3, "c"));
// 遍历
Map keyValueMap = new HashMap<>();
for (KeyValue keyValue : list) {
keyValueMap.put(keyValue.getKey(), keyValue.getValue());
}
keyValueMap.forEach((k, v) -> System.out.println(k + " ==> " + v));
// Java8 Stream
Map map = list.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue));
map.forEach((k, v) -> System.out.println(k + " ==> " + v));