Sunday, 6 March 2022

Java: retain all the matched strings in a collection

Below snippet retain all the strings that matches to any of the regular expressions.

 


Find the below working application.

 

RetainMatchedStrings.java
package com.sample.app.strings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

public class RetainMatchedStrings {

	public static void retainMatchedStrings(Collection<String> values, Collection<String> patterns) {

		if (values == null || values.isEmpty()) {
			return;
		}

		if (patterns == null || patterns.isEmpty()) {
			return;
		}

		List<String> matchedStrings = new ArrayList<String>();

		for (String patternToMatch : patterns) {
			Pattern pattern = Pattern.compile(patternToMatch);

			for (String value : values) {
				if (pattern.matcher(value).matches()) {
					matchedStrings.add(value);
				}
			}
		}
		values.retainAll(matchedStrings);

	}

	public static void main(String[] args) {

		List<String> strings = new ArrayList<>();
		strings.add("aab");
		strings.add("xyz");
		strings.add("ab");
		strings.add("fg");
		strings.add("de");

		List<String> patterns = Arrays.asList("a*b", "d*e");

		retainMatchedStrings(strings, patterns);

		System.out.println(strings);

	}
}

 

Output

[aab, ab, de]

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment