Java 8 For Loop code example

Example 1: java 8 loop in map

Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

items.forEach((k,v)->{
	System.out.println("Item : " + k + " Count : " + v);
	if("E".equals(k)){
		System.out.println("Hello E");
	}
});

Example 2: foreach java

for (String name : names) {
    System.out.println(name);
}

Example 3: inline foreach java

names.forEach(name -> System.out.println(name));

Example 4: loop in java 8

List<Integer> data = new ArrayList<>();

//Indexed Loop
for(int i = 0,size=data.size();i<size;i++){
	System.out.println(data.get(i));  
}

//For each loop
for(Integer element : data){
	System.out.println(element);
}

//Using forEach
data.forEach(System.out::println);

//Using Stream
data.stream().forEach(System.out::println)
  
//While loop
int i = 0;
while(i<data.size()){
	System.out.println(data.get(i++));  
}

Tags:

Java Example