0

I have created a large amount of People beans and was wanting to store them in some kind of data structure where I would be able to search for particular types of People beans (e.g. People beans with a last name of "Sanchez") as fast as possible (I don't want to use a DB by the way). Is the only way to loop over my beans and test currBean.getLastName().equals("Sanchez") for each bean?

I would like to be able to do something like the following:

List<PeopleBean> myPeople = myBeansDataStructure.getAll(new PeopleBean("John", "Sanchez", 36),
                            new Comparator<PeopleBean>() {
                                @Override
                                public int compare(PeopleBean b1, PeopleBean b2) {
                                    // search conditions
                                }
                            });

and have it return a collection of beans matching the search. My searches will always be of the same 'kind', i.e., I will be either searching for beans with a particular last name, first name, or age (or some permutation of the three) so could something using an overridden equals method in the bean be used?

3 Answers 3

2

I am surprised this isnt there in the library.. or is it?

Anyway, you can write your own

public interface Condition<T> {
    public bool satisfies(T t);
}

And write a generic searcher, which goes through the entire and applies this function to each of them and returns you a new of only the ones that return true.

Sign up to request clarification or add additional context in comments.

2 Comments

Java 8 provides similar functionality; see my answer as a reference.
@JoshM Yup I saw that.. Nice rep number by the way :P
2

You can use Java 8 (This is under the assumption that myBeansDataStructure is a Collection of some sort.):

List<PeopleBean> myPeople = myBeansDataStructure.stream().filter(person -> person.getLastName().equals("Sanchez")).collect(Collectors.toList());

Or you could try something like this:

List<PeopleBean> myPeople = myBeansDataStructure.stream().map(PeopleBean::getLastName).filter(lastName -> lastName.equals("Sanchez")).collect(Collectors.toList());

1 Comment

:( some mean upvoter broke your leetness.. guess I can +1 now
0

You can try this

    List<PeopleBean> list=new ArrayList<>();
    for(PeopleBean i:list){
        if(i.getName().equals("whatEverName")){
            //do something 
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.