Map traversal and conversion

Iterator -> forEach(java5) -> Lambda(java8)

Ways to traverse the map

1. Traverse key or value

// 遍历key
for (String key : map.keySet()) {
    
    
    System.out.println(key);
}

// 遍历value
for (String value : map.values()) {
    
    
    System.out.println(value);
}

2. Use Iterator to traverse (delete elements)

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    
    
    Map.Entry<String, String> entry = iterator.next();
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

3. Use entrySet to traverse (higher efficiency than Lambda)

for (Map.Entry<String, String> entry : map.entrySet()) {
    
    
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

4. Use Lambda expressions

map.forEach((k, v) -> System.out.println(k + " : " + v));

Way to choose

Original link: https://blog.csdn.net/yueaini10000/article/details/78933289

  • If you only get key or value, it is recommended to use keySet or values
  • If you need both key and value, it is recommended to use entrySet
  • If you need to delete elements during the traversal process, iterator is recommended
  • If you need to add elements during the traversal process, you can create a new temporary map to store the new elements, and after the traversal is completed, put the temporary map in the original map.

String to Map (jackson)

ObjectMapper mapper = new ObjectMapper();
TypeFactory factory = mapper.getTypeFactory();
// 类型:map,key,value
MapType mapType = factory.constructMapType(HashMap.class, String.class, String.class);
try {
    
    
    HashMap<String, String> map = mapper.readValue(str, mapType);
} catch (JsonProcessingException e) {
    
    
    e.printStackTrace();
}

Map to String

try {
    
    
    String str = new ObjectMapper().writeValueAsString(map);
} catch (JsonProcessingException e) {
    
    
    e.printStackTrace();
}

Guess you like

Origin blog.csdn.net/Dkangel/article/details/106838217