Summary of java List loop and Map loop
I made a summary of list and map. I didn’t have any technical content, so I just reviewed the API.
The test environment is under junit4, and it will be the same if you don’t write a main method by yourself.
First, there are three loops of List:
@Test public void ForListTest() { List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); // Iterator loop does not need to know the size and type of the collection, the best choice for (@SuppressWarnings("rawtypes") Iterator iterator = list.iterator(); iterator.hasNext();) { String list = (String) iterator.next(); System.out.println("01)Iterator for:===================================================================================================================================================== for the for loops not only need to know the size of the set, but also requires that it is ordered for (int i = 0; i < list.size(); i++) { System.out.println("03)for================================================================================================================================================================================================================================================================================================ } } Then there are four loops of Map:
@Test public void ForMapTest() { Map<String, String> map = new HashMap<String, String>(); map.put("01", "1"); map.put("02", "2"); map.put("03", "3"); map.put("04", "4"); map.put("05", "5"); Set<String> keySet = map.keySet(); //1.keyset's foreach method for (String key : keySet) { System.out.println("1)keyset:" + "key:" + key + " value:" + map.get(key)); } Set<Entry<String, String>> entrySet = map.entrySet(); //2.entryset iterator for (@SuppressWarnings("rawtypes") Iterator iterator = entrySet.iterator(); iterator.hasNext();) { @SuppressWarnings("unchecked") Entry<String, String> entry = (Entry<String, String>) iterator .next(); System.out.println("02)entrySet,iterator: key:" + entry.getKey() + " value:" + entry.getValue()); } //3. Recommended, maximum capacity for (Entry<String, String> entry : entrySet) { System.out.println("03)entrySet,foreach:key:" + entry.getKey() + " value:" + entry.getValue()); } Collection<String> values = map.values(); //4. Methods that only loop out value for (String value: values) { System.out.println("04)values, just for values,value:" + value); } }Thank you for reading, I hope it can help you. Thank you for your support for this site!