Searching for a record in a TreeSet on the fly

橙三吉。 提交于 2019-12-01 07:36:05

If you want to find all entries that start with the text (e.g. "f"), you can use the subSet(from, to) method, like this:

SortedSet<String> s = new TreeSet<String>(new Comparator<String>() {
  public int compare( String s1, String s2 ) {
    return s1.compareToIgnoreCase( s2 );
  }

});


s.add( "Erich" );
s.add( "Erica" );
s.add( "Erin" );
s.add( "Dave" );
s.add( "Thomas" );

SortedSet<String> result = s.subSet( "e", "e" + Character.MAX_VALUE ); //"e" represents the user input
System.out.println(result);//prints [Erica, Erich, Erin]

result = s.subSet( "Eric", "Eric" + Character.MAX_VALUE );
System.out.println(result); //prints [Erica, Erich]

result = s.subSet( "Erich", "Erich" + Character.MAX_VALUE );
System.out.println(result); //prints [Erich]

Since the toparameter to subset(from, to) is exclusive, you need something that will clearly be greater. In my example I simply added Character.MAX_VALUE but you might want to get some better upper bound. Note that this depends on your comparator, e.g. how it handles case differences etc.

If you want to filter using wildcards, like all texts containing the text (e.g. f would translate to *f*), you'd have to iterate over and check all the entries anyways. In that case you don't get any advantage using a sorted set.

Edit: updated the example to your data (adding me as well :) ).

You can use boolean startsWith(String prefix) method of java.lang.String class to check if which values in the set starts with the input string.

Ex :

public void getName(Set<String> t, String s)
    {
        for(String str : t) 
        {
            if(str.toLowerCase().startsWith(s.toLowerCase()))
                System.out.println(str);
        }
    }

input :

Set<String> test = new TreeSet<String>();

        test.add( "Erich" );
        test.add( "Erica" );
        test.add( "Erin" );
        test.add( "Dave" );
        test.add( "Thomas" );

if you call the method :

getName(test, "eri");

output will be :

Erica
Erich
Erin
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!