开发者

Searching Java Collection Against A String

开发者 https://www.devze.com 2023-02-04 04:53 出处:网络
I have a collection which has following structure... ArrayList<String[]> schools = new ArrayList<String[]>();

I have a collection which has following structure...

ArrayList<String[]> schools = new ArrayList<String[]>();

I als开发者_开发技巧o have a string say "United Berkley"

Now I want to search "schools" for the above mentioned string and return String[] if there is any match in any the String[] array.

I have that basic code but lost to find desired regex for it.

String target = this.Schools.get(s)[a];
if (target.matches("*")) {
   schools.add(this.Schools.get(s));
}


Your schools data structure looks a bit... weird.

Are you sure what you wanted is not ArrayList<String> ?

If that's the case, then you can just use:

if (schools.contains("United Berkley"))


How about this?

        List<String[]> schoolsList = new ArrayList<String[]>();
        String [] schools = {"United Berkley","Super Standford"};
        schoolsList.add(schools);
        String target = "United Berkley";
        for(String [] school:schoolsList){
            Arrays.sort(school);
            int position = Arrays.binarySearch(school,target);
            if(position>=0){
                System.out.println("Found target");
            }else{
                System.out.println("Target is not in the list");
            }
        }

prints "Found target".


Just use String.equals(your-String) and loop through the array to match the schools. Or use list.contains(your-String)
But I guess using a HashMap will provice better access times for that kind of things.


You don't need a regular expression to search for a known string - just use target.equals ("United Berkley"). You can make it easier on yourself by making sure that your String[] arrays are sorted - use Arrays.sort (...) to keep them in order and the use Arrays.binarySearch (...) to search them quickly.

I do question the layout of your data structures though - it doesn't seem like the most natural way to do what you want. A HashMap or even a simple sorted List would be better.


You don't need a regular expression to search for a known string - just use target.equals ("United Berkley"). You can make it easier on yourself by making sure that your String[] arrays are sorted - use Arrays.sort (...) to keep them in order and the use Arrays.binarySearch (...) to search them quickly.

I do question the layout of your data structures though - it doesn't seem like the most natural way to do what you want. A HashMap or even a simple sorted List seem more appropriate.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号