Below you can see an exemple how it works.
@Test public void myTestWithForEachOnly(){ // Create the list and itens List<String> myList = new ArrayList<String>(); myList.add("text Z"); myList.add("text B"); myList.add("text C"); Consumer myConsumer = new PrintTexts(); myList.forEach(myConsumer); } // Here you define what is to do for each item in the List public class PrintTexts implements Consumer<String>{ @Override public void accept(String s) { System.out.println(s); } }
Result in Console
Now the same code but better 😛 With lambdas
@Test public void myTestWithForEachAndLambdas(){ List<String> myList = new ArrayList<String>(); myList.add("text Z"); myList.add("text B"); myList.add("text C"); myList.forEach(words.forEach(s -> System.out.println(s)); }