Partially match strings in case of List.contains(String)

Viewed 34002

I have a List<String>

List<String> list = new ArrayList<String>();
list.add("ABCD");
list.add("EFGH");
list.add("IJ KL");
list.add("M NOP");
list.add("UVW X");

if I do list.contains("EFGH"), it returns true. Can I get a true in case of list.contains("IJ")? I mean, can I partially match strings to find if they exist in the list?

I have a list of 15000 strings. And I have to check about 10000 strings if they exist in the list. What could be some other (faster) way to do this?

Thanks.

9 Answers

This is not a direct answer to the given problem. But I guess this answer will help someone to compare partially both given and the elements in a list using Apache Commons Collections.

final Equator equator = new Equator<String>() {
        @Override
        public boolean equate(String o1, String o2) {
            final int i1 = o1.lastIndexOf(":");
            final int i2 = o2.lastIndexOf(":");
            return o1.substring(0, i1).equals(o2.substring(0, i2));
        }

        @Override
        public int hash(String o) {
            final int i1 = o.lastIndexOf(":");
            return o.substring(0, i1).hashCode();
        }
    };
    final List<String> list = Lists.newArrayList("a1:v1", "a2:v2");
    System.out.println(IteratorUtils.matchesAny(list.iterator(), new EqualPredicate("a2:v1", equator)));
Related