In this short Java tutorial I am going to share with you a few different ways you can use to iterate over a collection in Java.
Iterating List with Enhanced For-Loop
List<String> names = new ArrayList<>(); names.add("Sergey"); names.add("Bill"); names.add("John"); for(String name: names) { System.out.println(name); }
Iterating List with forEach() and Lambda
List<String> names = new ArrayList<>(); names.add("Sergey"); names.add("Bill"); names.add("John"); names.forEach(name -> System.out.println(name));
forEach, Stream, Filter and Lamda
List<String> names = new ArrayList<>(); names.add("Sergey"); names.add("Bill"); names.add("John"); names.stream().filter(s->s.contains("S")).forEach(name -> System.out.println(name));
Iterating List Using Iterator
List<String> names = new ArrayList<>(); names.add("Sergey"); names.add("Bill"); names.add("John"); Iterator iter = names.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); }
Iterating Over Map with Enhanced For-Loop
Map<String, String> keyValues = new HashMap<>(); keyValues.put("firstName", "Sergey"); keyValues.put("lastName", "Kargopolov"); keyValues.put("country", "Canada"); for (Map.Entry<String, String> entry : keyValues.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); }
Iterating Over Map with forEach() and Lambda
Map<String, String> keyValues = new HashMap<>(); keyValues.put("firstName", "Sergey"); keyValues.put("lastName", "Kargopolov"); keyValues.put("country", "Canada"); keyValues.forEach((key,value)->System.out.println(key + " : " + value));
Iterating Over Map Using EntrySet
Map<String, String> keyValues = new HashMap<>(); keyValues.put("firstName", "Sergey"); keyValues.put("lastName", "Kargopolov"); keyValues.put("country", "Canada"); keyValues.entrySet().forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue()));
I hope this short Java tutorial with code examples on how to iterate over a List and Map in Java was helpful for you.
If you are learning Java and enjoy learning by watching a series of step by step video lessons then have a look at the below list of video courses. One of them might help you to speed up your learning progress.