|
| 1 | +package com.baeldung.listregexfilter; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.regex.Matcher; |
| 7 | +import java.util.regex.Pattern; |
| 8 | +import java.util.stream.Collectors; |
| 9 | + |
| 10 | +public class RegexFilterExample { |
| 11 | + |
| 12 | + public List<String> filterUsingPatternAndPredicate() { |
| 13 | + List<String> fruits = List.of("apple", "banana", "cherry", "apricot", "avocado"); |
| 14 | + |
| 15 | + Pattern pattern = Pattern.compile("^a.*"); |
| 16 | + |
| 17 | + return fruits.stream() |
| 18 | + .filter(pattern.asPredicate()) |
| 19 | + .toList(); |
| 20 | + } |
| 21 | + |
| 22 | + public List<String> filterUsingStringMatches() { |
| 23 | + List<String> list = List.of("123", "abc", "456def", "789", "xyz"); |
| 24 | + |
| 25 | + return list.stream() |
| 26 | + .filter(str -> str.matches("\\d+")) |
| 27 | + .toList(); |
| 28 | + } |
| 29 | + |
| 30 | + public List<String> filterUsingPatternCompile() { |
| 31 | + List<String> numbers = List.of("one", "two", "three", "four", "five"); |
| 32 | + List<String> startWithTList = new ArrayList<>(); |
| 33 | + |
| 34 | + Pattern pattern = Pattern.compile("^t.*"); |
| 35 | + |
| 36 | + for (String item : numbers) { |
| 37 | + Matcher matcher = pattern.matcher(item); |
| 38 | + if (matcher.matches()) |
| 39 | + startWithTList.add(item); |
| 40 | + } |
| 41 | + |
| 42 | + return startWithTList; |
| 43 | + } |
| 44 | + |
| 45 | + public Map<Boolean, List<String>> filterUsingCollectorsPartitioningBy() { |
| 46 | + List<String> fruits = List.of("apple", "banana", "apricot", "berry"); |
| 47 | + |
| 48 | + Pattern pattern = Pattern.compile("^a.*"); |
| 49 | + |
| 50 | + return fruits.stream() |
| 51 | + .collect(Collectors.partitioningBy(pattern.asPredicate())); |
| 52 | + } |
| 53 | + |
| 54 | + public static void main(String[] args) { |
| 55 | + RegexFilterExample regexFilterExample = new RegexFilterExample(); |
| 56 | + regexFilterExample.filterUsingPatternAndPredicate(); |
| 57 | + regexFilterExample.filterUsingStringMatches(); |
| 58 | + regexFilterExample.filterUsingPatternCompile(); |
| 59 | + regexFilterExample.filterUsingCollectorsPartitioningBy(); |
| 60 | + } |
| 61 | +} |
0 commit comments