Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element without iterating

I have an ArrayList of HashMap key-value pairs which looks like

ArrayList<HashMap<String, String>> myList = 
            new ArrayList<HashMap<String, String>>();

I understand that I can iterate through these items and find a match, but this seems to be an expensive task. Is there any other way to get an element without iterating?

My ArrayList has values like

[{Father Name=a, Mother Name=b, Child Name=c, Reg No=1, Tag ID=1}, 
{Father Name=p, Mother Name=q, Child Name=r, Reg No=2, Tag ID=2}, 
{Father Name=x, Mother Name=y, Child Name=z, Reg No=3, Tag ID=3}]

Based on RegNo, I wish to get Father Name, Mother Name and Child Name without iterating individual items.

like image 315
Jigskep Avatar asked Nov 29 '25 09:11

Jigskep


1 Answers

Without iterating you will need to store your HashMap in another HashMap with key Reg No. Though I'd recommend using a Family object or something similar: HashMap<Integer, Family> registration (that's the beauty of OO-languages :) )

class Family {
    String father;
    String mother;
    String child;

    // constructor getters setters
}

Map<Integer, Family> registration = new HashMap(); // note this is a JDK7 future 
//Map<Integer, Family> registration = new HashMap<Integer, Family>(); // the 'old' way
registration.put(regNo, new Family("Jack", "Mary", "Bastard"));

Family family = registration.get(regNo);
String father = family.getFather();
like image 56
Menno Avatar answered Dec 01 '25 22:12

Menno