Pages

Wednesday, July 1, 2015

Java 8 lambda examples

Input file :
 10 
 -20  
 30

Read a file line by line and print :
     try (BufferedReader reader = new BufferedReader(  
         new InputStreamReader(Example.class.getResourceAsStream("/input.txt")))) {  
       reader.lines().forEach(line -> System.out.println(line));  
     } catch (IOException e) {  
       throw new RuntimeException(e);  
     }  

or collect them in a list:

       List<String> lineList = reader.lines()
                                           .collect(Collectors.toList());  

or sum all the numbers:

       int sum = reader.lines()
                       .mapToInt(line -> Integer.parseInt(line)).sum();  

or maybe just add only the positive values:
      
       int sum = reader.lines()
                       .mapToInt(line -> Integer.parseInt(line))
                       .filter(anInt -> anInt > 0).sum();   

No comments:

Post a Comment