Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Created October 15, 2017 01:04
Show Gist options
  • Save jsbonso/7ac9af1f098ba03ff9753057c327c0a5 to your computer and use it in GitHub Desktop.
Save jsbonso/7ac9af1f098ba03ff9753057c327c0a5 to your computer and use it in GitHub Desktop.
Java Stream Filter Examples
/**
* filter() example of Java's Stream API
*
*
* How to get certain items from a collection using the filter()
* intermediate operation, and then show the result using the
* collect() terminal operation.
*
* @author jonbonso
* @param args
*/
public static void main(String... args) {
List<Integer> numList = new LinkedList<>();
for (int i=1; i<= 10; i++)
numList.add(i);
System.out.println(" numList size: " + numList.size() + "\n" +
" numList contents: " + numList);
System.out.println("\n Using the old & verbose way of list iteration and if statement");
List<Integer> oldWayNumList = numList;
Iterator<Integer> itr = oldWayNumList.iterator();
while(itr.hasNext()) {
if( itr.next() <= 5) {
itr.remove();
}
}
System.out.println("\t numList contents: " + numList);
System.out.println("\n Using the Java 8's Stream Filter");
System.out.println("\t Filtering the List to only contains number greater than 5...");
Stream<Integer> numStreamGreaterThan5 =
numList.stream()
.filter(
// Use the lambda expression (->) and
// supply the filter condition, which is the num
// should be greater to 5.
n -> (n > 5)
);
System.out.println("\t numStream contents: " +
numStreamGreaterThan5.collect(Collectors.toList()) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment