How to iterate List using Java 8

In this post we will see how to Iterate a Java List Using Java 8 with few examples.

Java 7 and Prior:

Before Java 8, Using loop (for, while, do-while), list can be iterated. Enhanced Loop can also be used to iterate a loop.

	static List<String> getLists() {
		List<String> lists = new ArrayList<String>();
		lists.add("One");
		lists.add("Two");
		lists.add("Three");
		lists.add("Four");
		lists.add("Five");
		return lists;
	}

	
	public static void printUsingEnhancedLoop() {
		System.out.println("Using Enhanced Loop");
		for (String value : getLists()) {
			System.out.println(value);
		}
	}

Output

Using Enhanced Loop
One
Two
Three
Four
Five

How to iterate List using Java 8:

In Java 8, forEach statement  can be used to iterate a list.

	public static void printWithoutMethodRef() {
		System.out.println("Without Method Reference");
		getLists()
		.forEach(value -> System.out.println(value));
	}

Output

Without Method Reference
One
Two
Three
Four
Five

Method Reference

Method Reference can also be used to print the values

public static void printWithMethodRef() {
		System.out.println("With Method Reference");
		getLists()
		.forEach(System.out::println);
}

Output

With Method Reference
One
Two
Three
Four
Five

Conditional statements

Conditional statements can be applied using if statement.

public static void printUsingFilterOne() {
		System.out.println("Conditional Statement");
		getLists()
			.forEach(value -> {
				if (value.equals("One")) {
					System.out.println(value);
				}
		});
	}

Output

 
Conditional Statement 
One 

Filter() method

Conditional statements can also be applied using filter() method, for which stream() method should be applied first.

public static void printUsingFilterTwo() {
		System.out.println("Using Filter");
		getLists()
		.stream()
		.filter(value -> value.equals("Two"))
		.forEach(System.out::println);
	}

Output

Using Filter
One

Code

How to iterate List using Java8

 

Add a Comment

Your email address will not be published. Required fields are marked *