Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Java Stream and Lambda examples for my sister
import java.util.Arrays;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
public class StreamExamples {
public static void main(String[] args) {
int[] myData = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34};
System.out.println("myData: " + Arrays.toString(myData));
System.out.println("Odd only: " + Arrays.toString(oddOnly(myData)));
System.out.println("Multiplied by 2: " + Arrays.toString(multiply(myData, 2)));
System.out.println("Sum: " + sum(myData));
IntUnaryOperator squareOp = i -> i * i;
System.out.println("Squared: " + Arrays.toString(doUnaryOperation(myData, squareOp)));
int[] myOtherData = new int[]{1, 2, 4, 8, 16, 32, 64, 128, 256};
System.out.println("myOtherData: " + Arrays.toString(myOtherData));
System.out.println("Combined with myData: " + Arrays.toString(combine(myData, myOtherData)));
}
private static int[] oddOnly(int[] data) {
return Arrays.stream(data) // convert array to stream
.filter(i -> i % 2 != 0) // filter for all odd elements
.toArray(); // convert back to array
}
private static int[] multiply(int[] data, int multiple) {
return Arrays.stream(data)
.map(i -> i * multiple)
.toArray();
}
private static int[] combine(int[] data1, int[] data2) {
assert data1.length == data2.length;
return IntStream.range(0, data1.length)
.map(i -> data1[i] + data2[i])
.toArray();
}
private static int sum(int[] data) {
return Arrays.stream(data).sum();
}
private static int[] doUnaryOperation(int[] data, IntUnaryOperator op) {
return Arrays.stream(data)
.map(op)
.toArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment