java.util.stream adds support for functional-style operations on streams of elements. This opens up huge possibilities. A major outcome is that traditional for-loops might not exist as we know them. Gone are their days. So what come as replacement?
There you go! Right question. Already on the mark.
Let's see some examples.
Above piece of code is a traditional for loop, which returns the Opening Batsmen.. Same code can now be written as below without the for loop.
Nice! Used filter to filter out the Opening Batsmen and return the first one of all.
There are two Opening Batsmen. How to get both of them.
Below is the code both in traditional for-loop and the new Streams
There can be innumerable example of replacing for-loops. Explore them and start using the power of Java 8.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Cricketer getOpeningBatsmen() { | |
for (Cricketer cricketer : cricketets) { | |
if (cricketer.getPosition().contains("Opener")) { | |
return cricketer; | |
} | |
} | |
return null; | |
} |
Above piece of code is a traditional for loop, which returns the Opening Batsmen.. Same code can now be written as below without the for loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Cricketer getOpeningBatsmen() { | |
for (Cricketer cricketer : cricketets) { | |
if (cricketer.getPosition().contains("Opener")) { | |
return cricketer; | |
} | |
} | |
return null; | |
} |
Nice! Used filter to filter out the Opening Batsmen and return the first one of all.
There are two Opening Batsmen. How to get both of them.
Below is the code both in traditional for-loop and the new Streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Traditional For Loop | |
public List<Cricketer> getAllOpeningBatsmen() { | |
List<Cricketer> openingBatsmen = new ArrayList<>(); | |
for (Cricketer cricketer : cricketers) { | |
if (cricketer.getPosition().contains("Opener")) { | |
openingBatsmen.add(cricketer); | |
} | |
} | |
return openingBatsmen; | |
} | |
// Java 8 Using Streams | |
public List<Cricketer> getAllOpeningBatsmen() { | |
return cricketers.stream() | |
.filter(cricketer -> cricketer.getPosition().contains("Opener")) | |
.collect(Collectors.toList()); | |
} |
There can be innumerable example of replacing for-loops. Explore them and start using the power of Java 8.
No comments:
Post a Comment