Skip to content

Instantly share code, notes, and snippets.

@Nicklas2751
Created May 25, 2017 23:25
Show Gist options
  • Save Nicklas2751/ad5dcae65a6ecb9de05177e26aff1637 to your computer and use it in GitHub Desktop.
Save Nicklas2751/ad5dcae65a6ecb9de05177e26aff1637 to your computer and use it in GitHub Desktop.
A example how to use java 8 lambda stream with inputstream and map.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LambdaInputStreamMapExample {
public static void main(String[] args) {
new LambdaInputStreamMapExample().start();
}
// Example Input: I'm the real Donald Trump
// Output: Line: "I'm the real Donald Drumpf"
private void start() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
//Get Stream with lines from BufferedReader
reader.lines()
//Gives each line as string to the changeTrumpToDrumpf method of this.
.map(this::changeTrumptoDrumpf)
//Calls for each line the print method of this.
.forEach(this::print);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private String changeTrumptoDrumpf(String aLine) {
// https://en.wikipedia.org/wiki/Donald_Trump_(Last_Week_Tonight)#.22Make_Donald_Drumpf_Again.22
return aLine.replaceAll("Trump", "Drumpf");
}
private void print(String aLine) {
System.out.println(String.format("Line: \"%s\"", aLine));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment