Created
April 17, 2014 18:29
-
-
Save bdkosher/11003235 to your computer and use it in GitHub Desktop.
Java 8 Lambda examples from Simon Ritter's QCon presentation: http://www.infoq.com/presentations/lambda-streams-java-8
This file contains hidden or 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
// Ex 1: Convert words in list to upper case | |
List<String> output = wordList.stream() | |
.map(String::toUpperCase) | |
.collect(Collectors.toList()); | |
// Ex 2: Finds words in list with even length | |
List<String> output = wordList.stream() | |
.filter(w -> w.length() & 1 == 0) | |
.collect(Collectors.toList()); | |
// Ex 3: Count lines in a file | |
long count = bufferedReader.lines().count(); | |
// Ex 4: Join lines 3-4 into a single string | |
String output = bufferedReader.lines() | |
.skip(2) | |
.limit(2) | |
.collect(Collectors.joining()); | |
// Ex 5: Find length of longest line in a file | |
int longest = reader.lines() | |
.mapToInt(String::length) | |
.max() | |
.getAsInt(); | |
// Ex 6: Collect all words in a file into a list | |
List<String> output = reader.lines() | |
.flatMap(line -> Stream.of(line.split(REGEXP))) | |
.filter(word -> word.length() > 0) | |
.collect(Collectors.toList()); | |
// Ex 7: List of words lowercased, in alphabetical order | |
List<String> output = reader.lines() | |
.flatMap(line -> Stream.of(line.split(REGEXP))) | |
.filter(word -> word.length() > 0) | |
.map(String::toLowerCase) | |
.sorted() | |
.collect(Collectors.toList()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment