Created
August 6, 2017 08:51
-
-
Save mismatch/19d20828a170d85b1dd65730e40f0604 to your computer and use it in GitHub Desktop.
In response to https://stackoverflow.com/questions/45528735/reusing-the-same-value-inside-of-a-java-stream
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 class EquationStream { | |
public static void main(String[] args) { | |
List<Month> months = new ArrayList<>(12); | |
months.add(new Month(1, "January")); | |
months.add(new Month(2, "February")); | |
months.add(new Month(3, "March")); | |
months.add(new Month(4, "April")); | |
months.add(new Month(5, "May")); | |
months.add(new Month(6, "June")); | |
months.add(new Month(7, "July")); | |
months.add(new Month(8, "August")); | |
months.add(new Month(9, "September")); | |
months.add(new Month(10, "October")); | |
months.add(new Month(11, "November")); | |
months.add(new Month(12, "December")); | |
int[] res = months.stream() | |
.map(month -> new Pair(month.number, month.number * 2)) | |
.map(pair -> new Pair(pair.x, pair.y + 10)) | |
.map(pair -> new Pair(pair.x, pair.y / 2)) | |
.map(pair -> new Pair(pair.x, pair.y - pair.x)) | |
.mapToInt(pair -> pair.y) | |
.toArray(); | |
System.out.println("Result is " + Arrays.toString(res)); | |
} | |
private static class Month { | |
int number; | |
String name; | |
public Month(int month, String name) { | |
this.number = month; | |
this.name = name; | |
} | |
} | |
private static class Pair { | |
int x; | |
int y; | |
public Pair(int x, int y) { | |
this.x = x; | |
this.y = y; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment