How to traverse Map and List in Java (Loop, Loop)

iteration

Everyone must have used Maps and Lists a lot while developing in Java. In my case, List loop is easy to implement, but Map always checks other code and code. I don`t use it often, so I forget it every time. So, I took this opportunity to summarize it briefly.

Map의 iteration

There are two ways to implement the Map loop, a general method and a Java8 Lambda expression. The codes below all output the same content.

// Loop a Map
Map<String, String>  cities = new HashMap<>();
cities.put("Tokyo", "Japan");
cities.put("Seoul", "Korea");
cities.put("Beijing", "China");
cities.put("Paris", "France");
cities.put("Washington", "USA");
cities.put("Brazilia", "Brazil");

// Normal ways
//1)
for (Map.Entry<String, String> entry : cities.entrySet()) {
    System.out.println("Cities: " + entry.getKey() + ", " + entry.getValue());
}

//2)
for (String key : cities.keySet()) {
    System.out.println("Cities: " + key + ", " + cities.get(key));
}

// Java8 forEach, Lambda
// 1)
cities.forEach((k, v) -> System.out.println("Cities: " + k + ", " + v));

// 2)
cities.forEach((k, v) -> {
    System.out.println("Cities: " + k + ", " + v);
});

result

Cities: Beijing, China
Cities: Tokyo, Japan
Cities: Seoul, Korea
Cities: Brazilia, Brazil
Cities: Paris, France
Cities: Washington, USA
...

List의 iteration

There are two ways to implement a list loop, the general method as above and the use of Lambda. The codes below all output the same content.

// Loop a List
List<String> fruits = new ArrayList<>();
fruits.add("banana");
fruits.add("apple");
fruits.add("peach");
fruits.add("lemon");
fruits.add("mango");

// Normal way
// 1)
for (String item : fruits) {
    System.out.println("Fruits: " + item);
}

// Java8 forEach, Lambda, Stream
// 1)
fruits.forEach(item -> System.out.println("Fruits: " + item));

// 2)
fruits.forEach(item -> {
    System.out.println("Fruits: " + item);
});

// 3)
fruits.stream()
    .forEach(item -> System.out.println("Fruits: " + item));

result

Fruits: banana
Fruits: apple
Fruits: peach
Fruits: lemon
Fruits: mango
...
codechachaCopyright ©2019 codechacha