Java forEach examples

This article lists some examples of forEach loop with Collections.
 

forEach example with Array

String[] countries = { "india", "usa", "china", "russia" };

System.out.println("array contents : ");

for (String str : countries) {
  System.out.println(str);
}

 

forEach example with List

List<String> countries = new ArrayList<String>();
countries.add("india");
countries.add("usa");
countries.add("china");
countries.add("russia");

for (String str : countries) {
  System.out.println(str);
}

 
With Java8, we can also use the lambda expression in following way :

countries.forEach(e -> System.out.println(e));

 

forEach example with Map

Map<String, String> countryCapitalMap = new HashMap<String, String>();
countryCapitalMap.put("guyana", "georgetown");
countryCapitalMap.put("nepal", "kathmandu");
countryCapitalMap.put("australia", "canberra");
countryCapitalMap.put("india", "new delhi");
countryCapitalMap.put("japan", "tokyo");

for (Map.Entry<String, String> entry : countryCapitalMap.entrySet()) {
  System.out.println(entry.getKey() + " : " + entry.getValue());
}

 
With Java8, we can also use the lambda expression in following way :

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

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] Java foreach examples […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: