Created
June 27, 2022 09:29
-
-
Save zhangr4/8938602c3e1260742d8c0cd5f58b4db7 to your computer and use it in GitHub Desktop.
static functions for filter() and map() in Java 8 - 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
import java.util.function.Function; | |
import java.util.function.Predicate; | |
import java.util.regex.Pattern; | |
import java.util.stream.Stream; | |
import java.util.Arrays; | |
/* raw problem and better solution: | |
https://stackoverflow.com/questions/57836937/call-custom-static-functions-from-filter-and-map-in-java-8-stream | |
*/ | |
class Solution { | |
public static void main(String[] args) { | |
String[] arr = {"aac", "abc"}; | |
Stream<String> stream = Arrays.stream(arr); | |
stream.filter(DemoFilter.checkPrefixExist("aa")).map(DemoMap.numberOfDistinctCharacters()).forEach(s -> System.out.println(s)); | |
} | |
} | |
class DemoFilter { | |
public static Predicate<String> checkPrefixExist(String prefix) { | |
Pattern pattern = Pattern.compile(prefix); | |
return p -> pattern.matcher(p).find(); | |
} | |
} | |
class DemoMap { | |
public static Function<String, Integer> numberOfDistinctCharacters() { | |
return s -> (int)s.chars().distinct().count(); | |
} | |
} | |
// better solution: https://stackoverflow.com/questions/57836937/call-custom-static-functions-from-filter-and-map-in-java-8-stream |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment