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遍历
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);

// Java8 Lambda
map.forEach((k, v) -> System.out.println(k + " ==> " + v));

2. Map转List

@Data
@NoArgsConstructor
@AllArgsConstructor
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);

3. List转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));

// Java8 Stream
Map<Integer, String> map = list.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue));
map.forEach((k, v) -> System.out.println(k + " ==> " + v));
posted @ 2020-05-27 19:53  C3Stones  阅读(6348)  评论(0编辑  收藏  举报