Java – Iterating List and Map using forEach option

 


package com.pwn.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IteratingCollections {

	public static void main(String[] args) {
		List<String> fruitList = new ArrayList<>(
				Arrays.asList("Apple", "Banana", "Grape"));
		System.out.println(
				"***************Iterate List***********************");
		fruitList.forEach(System.out::println);
		System.out.println(
				"***************Iterate Map***********************");
		Map<Integer, String> fruitMap = new HashMap<>();
		fruitMap.put(1, "Apple");
		fruitMap.put(2, "Banana");
		fruitMap.put(3, "Grape");

		fruitMap.forEach((key, value) -> System.out
				.println("Key: " + key + " Value: " + value));

	}

}
***************Iterate List***********************
Apple
Banana
Grape
***************Iterate Map***********************
Key: 1 Value: Apple
Key: 2 Value: Banana
Key: 3 Value: Grape

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s