Search an attribute inside a Vector on Java

10,012

Solution 1

I assume that your problem is that you want to have a method that searches for a result based on some property of the collection type. Java is weak on this because it is best expressed in a language which has closures. What you need is something like:

public interface Predicate<T> {
    public boolean evaluate(T t);
}

And then your search method looks like:

public static <T> T findFirst(List<T> l, Predicate<T> p) { //use List, not Vector
    for (T t : l) { if (p.evaluate(t)) return t; }
    return null;
}

Then anyone can use this general-purpose search method. For example, to search for an number in a vector of Integers:

List<Integer> is = ...
findFirst(is, new Predicate<Integer> {
    public boolean evaluate(Integer i) { return i % 2 == 0; }
});

But you could implement the predicate in any way you want; for any arbitrary search

Solution 2

Use Collections.binarySearch and provide a Comparator.

EDIT: This assumes that the Vector is sorted. Otherwise, one has to do a linear search.

Share:
10,012
PotterSys
Author by

PotterSys

Jerk of All Trades

Updated on June 04, 2022

Comments

  • PotterSys
    PotterSys almost 2 years

    I've a Vector of objects, and have to search inside for a random attribute of those objects (For example, a Plane class, a Vector containing Plane; and I've to search sometimes for destination, and others to pilotName).

    I know I can traverse the Vector using an Iterator, but I've got stuck at how do I change the comparison made between a String and the attribute on the object. I thought of using switch, but a another opinion would be cool.


    Update 1:

    The code I've written is something like this (Java n00b alert!):

    public int search(String whatSearch, String query){  
        int place = -1;  
        boolean found = false;  
        for ( Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false; ) {  
            Plane temp = (Plane) iteraPlane.next();  
            /* Here is where I have to search for one of many attributes (delimited by whatSearch */ 
        }  
    return place;  
    }
    

    Seems I've to stick to linear search (and that's a price I've able to pay). Anyway, I was thinking if Java had something like variable variable name (ouch!)