Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query inmemory objects by attribute?

Tags:

java

I'm getting a list of 300 json objects that are to be cached in memory for a day. During execution of the application I want to query objects by their properties.

Example:

@XmlRootElement(name = "persons")
@XmlAccessorType(XmlAccessType.FIELD)
class PersonsDTO {
    private List<PersonDTO> persons;

    public static class PersonDTO {
        private String name;
        private int age;
        //lots of more attributes
        private Address address;
    }
}

Here I'd like to run queries similar to a database, like:

findByname("john doe");
findByAgeBetween(10, 18);

Question: how could I best prepare the data for those "query" lookups? Create a HashMap for each query function where I then could just return the precalculated results?

Or is there any "database-like" inmemory system that I could use and that can be queried similar to a real database?

like image 444
membersound Avatar asked May 05 '26 03:05

membersound


1 Answers

I would just brute force it unless you have specific performance requirements. Scanning 300 entries should take less than 0.1 ms.

This would allow you to use the streams API built in.

private List<PersonDTO> persons;

public List<PersonDTO> findBy(Predicate<PersionDTO> test) {
    return persons.stream().filter(test).collect(Collectors.toList());
}


// findByName
List<PersonDTO> david = findBy(p -> p.getName().startsWith("David "));

// find by age
List<PersonDTO> youngAdult= findBy(p -> p.getAge() >= 18 && p.getAge() <= 30);
like image 196
Peter Lawrey Avatar answered May 07 '26 16:05

Peter Lawrey