HashSet Override Contains a Method

Can someone tell me how I can override the HashSet contains () method to use regular match instead of equals ()?

Or, if not overridden, how can I add a method to use the regex pattern? Basically, I want to be able to run a regular expression on strings containing a HashSet, and I need to fine-tune the substrings with the regular expression.

If my method does not work, ask others.

Thank.:)

+3
source share
2 answers

You can extend the HashSet as follows:

public class RegExHashSet extends HashSet<String > {
    public boolean containsRegEx( String regex ) {
        for( String string : this ) {
            if( string.matches( regex ) ) {
                return true;
            }
        }
        return false;
    }
}

Then you can use it:

RegExHashSet set = new RegExHashSet();
set.add( "hello" );
set.add( "my" );
set.add( "name" );
set.add( "is" );
set.add( "tangens" );

if( set.containsRegEx( "tan.*" ) ) {
    System.out.println( "it works" );
}
+5
source
+2

Source: https://habr.com/ru/post/1727525/


All Articles