Skip to content

Instantly share code, notes, and snippets.

@CalebFenton
Created October 17, 2016 20:37
Show Gist options
  • Save CalebFenton/8c712b0d5d80b91876f2bd59baee6e02 to your computer and use it in GitHub Desktop.
Save CalebFenton/8c712b0d5d80b91876f2bd59baee6e02 to your computer and use it in GitHub Desktop.
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