<> ergodic HashMap
Map<Integer, String> map = new HashMap<>(); map.put(1, "aaa"); map.put(2, "bbb"
); map.put(3, "ccc"); map.put(4, "ddd");
*
Common use , Second value
for(String key : map.keySet()){ System.out.println(key + ":" + map.get(key)); }
*
iterator entrySet
Iterator<Map.Entry<Integer, String>> mapiter = map.entrySet().iterator(); while
(mapiter.hasNext()) { @SuppressWarnings("unchecked") Map.Entry<Integer, String>
entry= mapiter.next(); System.out.println(entry.getKey() + ": " + entry.getValue
()); }
*
recommend , Especially when the capacity is large
for(Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(
entry.getKey() + ": " + entry.getValue()); }
*
Traverse all value, But not traversal key
for(String str : map.values()) { System.out.println(str); }
*
iterator keySet
Iterator<Integer> iter = map.keySet().iterator(); while(iter.hasNext()) { int
key= iter.next(); System.out.println(key + ": " + map.get(key)); }
*
lambda expression
map.forEach((key, value) ->{ System.out.println(key + ": " + value); });
*
Streams API Single thread
map.entrySet().stream().forEach((entry) ->{ System.out.println(entry.getKey() +
": " + entry.getValue()); });
<>Iterator Dynamic deletion of traversal
Map<Integer, String> map = new HashMap<>(); map.put(1, "aaa"); map.put(2, "bbb"
); map.put(3, "ccc"); map.put(4, "ddd"); Iterator<Integer> iter = map.keySet().
iterator(); while(iter.hasNext()) { int key = iter.next(); System.out.println(
key+ ": " + map.get(key)); if(key == 2) { iter.remove(); } } Iterator<Map.Entry<
Integer, String>> mapiter = map.entrySet().iterator(); while(mapiter.hasNext())
{ @SuppressWarnings("unchecked") Map.Entry<Integer, String> entry = mapiter.next
(); System.out.println(entry.getKey() + ": " + entry.getValue()); if(entry.
getKey() == 2) { mapiter.remove(); } }
<>Arrays.asList()
Use tool class Arrays.asList() When converting an array to a collection , You cannot use it to modify collection related methods , its add/remove/clear Method will throw UnsupportedOperationException abnormal
【 explain
】asList() The return object of is a Arrays Inner class , There is no way to modify the collection .Arrays.asList It embodies the adapter pattern , It's just a converter , The data in the background is still an array
【 be careful 】
* The array passed must be an array of objects , Not the basic type
* Modifying methods using sets add()/remove()/clear() Will throw an exception
* List<String> list = new ArrayList<String>(Arrays.asList("aaa", "bbb",
"ccc"))
Technology
Daily Recommendation