Searching for a record in a TreeSet on the fly

前端 未结 2 1316
不思量自难忘°
不思量自难忘° 2021-01-14 01:31

I\'m writing a contact book application in Java using the swing and awt libraries. The Application consists of a JList which uses a TreeSet as an abstractListModel.

2条回答
  •  甜味超标
    2021-01-14 02:32

    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 t, String s)
        {
            for(String str : t) 
            {
                if(str.toLowerCase().startsWith(s.toLowerCase()))
                    System.out.println(str);
            }
        }
    

    input :

    Set test = new TreeSet();
    
            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
    

提交回复
热议问题