Java foreach Example - List | Map | Set - Java 8 Lambdas - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Friday, December 29, 2017

Java foreach Example - List | Map | Set - Java 8 Lambdas



List

  List<String> colourList = new ArrayList<>();
  colourList.add("RED");
  colourList.add("GREEN");
  colourList.add("BLUE");
  colourList.add("YELLOW");
  colourList.add("BLACK");
  colourList.add("WHITE");

  for (String color : colourList){
      System.out.println( color );
  }

Java 8 Lambdas

  colourList.forEach(color -> System.out.println(color));

Map

  Map<Integer, String> colourMap = new HashMap<>();
  colourMap.put(1, "RED");
  colourMap.put(2, "GREEN");
  colourMap.put(3, "BLUE");
  colourMap.put(4, "YELLOW");
  colourMap.put(5, "BLACK");
  colourMap.put(6, "WHITE");

  for (Map.Entry<Integer, String> color : colourMap.entrySet()){
System.out.println( color.getKey() + " -> " + color.getValue());
  }

Java 8 Lambdas

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

Set

  Set<String> colourSet = new HashSet<>();
  colourSet.add("RED");
  colourSet.add("GREEN");
  colourSet.add("BLUE");
  colourSet.add("YELLOW");
  colourSet.add("BLACK");
  colourSet.add("WHITE");

  for (String color : colourSet){
System.out.println( color);
  }

Java 8 Lambdas

  colourSet.forEach(color -> System.out.println(color));

Look for the null values !

  List<String> nullList = null;

  for (String item : nullList){
System.out.println( item);
  }

Exception in thread "main" java.lang.NullPointerException


References

https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html


No comments:

Post a Comment