Created
December 17, 2016 04:14
-
-
Save ru-rocker/1a0cd8d33938342e450329db09e9848a to your computer and use it in GitHub Desktop.
Java 8 Stream Match sample. Using anyMatch, allMatch and noneMatch
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
//there is at least one negative number | |
public void anyMatch(){ | |
boolean anyMatch; | |
anyMatch = IntStream.of(-1,2,3,5,7,9) | |
.anyMatch(i -> i < 0); | |
System.out.format("It is [%b] that at least one negative number \n", | |
anyMatch); | |
//Output: It is [true] that at least one negative number | |
anyMatch = IntStream.of(2,3,5,7,9) | |
.anyMatch(i -> i < 0); | |
System.out.format("It is [%b] that at least one negative number \n", | |
anyMatch); | |
//Output: It is [false] that at least one negative number | |
} | |
//all numbers are positive | |
public void allMatch(){ | |
boolean allMatch; | |
allMatch = IntStream.of(1, 4, 10, 3, 9) | |
.allMatch(i -> i >= 0); | |
System.out.format("It is [%b] that all numbers are postive \n", | |
allMatch); | |
//Output: It is [true] that all numbers are positive | |
allMatch = IntStream.of(1, 4, 10, -3, 3, 9) | |
.allMatch(i -> i >= 0); | |
System.out.format("It is [%b] that all numbers are postive \n", | |
allMatch); | |
//Output: It is [false] that all numbers are positive | |
//but we can use a negation here, using none match | |
allMatch = IntStream.of(1, 4, 10, 3, 9) | |
.noneMatch(i -> i < 0); | |
System.out.format("It is [%b] that all numbers are postive \n", | |
allMatch); | |
//Output: It is [true] that all numbers are positive | |
} | |
//all numbers are negative | |
public void noneMatch(){ | |
boolean noneMatch; | |
noneMatch = IntStream.of(1, 4, 10, 3, 9, -1, -10) | |
.noneMatch(i -> i >= 0); | |
System.out.format("It is [%b] that all numbers are negative \n", | |
noneMatch); | |
//Output: It is [false] that all numbers are negative | |
noneMatch = IntStream.of(-1, -4, -10, -3, -3, -9) | |
.noneMatch(i -> i >= 0); | |
System.out.format("It is [%b] that all numbers are negative \n", | |
noneMatch); | |
//Output: It is [true] that all numbers are negative | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment