Summary of java List loop and Map loop
- 2020-05-17 05:25:07
- OfStack
Summary of java List cycle and Map cycle
I made a summary of list and map. Without any technical content, I just reviewed api.
The test environment is under junit4. If you do not write one main method by yourself, it will be the same.
The first is the three cycles 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");
// The 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 : ===============" + list);
}
// foreach compared for You don't need to know the length of the set
for (String list : list) {
System.out.println("02)foreach:=================" + list);
}
// for Loops both need to know the size of the set and need to be ordered
for (int i = 0; i < list.size(); i++) {
System.out.println("03)for==================" + list.get(i));
}
}
Then there are the four cycles 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 the foreach methods
for (String key : keySet) {
System.out.println("1)keyset:" + "key:" + key + " value:"
+ map.get(key));
}
Set<Entry<String, String>> entrySet = map.entrySet();
//2.entryset Iterative approach
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. Only loop out value The method of
for (String value : values) {
System.out.println("04)values,just for values,value:" + value);
}
}
Thank you for reading, I hope to help you, thank you for your support of this site!