简体   繁体   中英

Selecting certain data from ArrayList

I wondering if there is anyway that if I know one part of an ArryList that I can find out the other. The problem I'm running into is my limited knowledge of java.

I have the list set up as:

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

The activity goes through and adds every spot(from a server) to the list in a forloop with PID and NAME as:

HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
spotsList.add(map);

Now is there a way I can get the name if I know the PID?

Thank you in advance,

Tyler

It seems that you expect the PIDs to be unique (given a PID you can find the corresponding name). So instead of a list of maps you should probably just use one map:

Map<String, String> map = new HashMap<String, String>();
for (Spot s : spots) map.put(s.id, s.name);

Retrieving a name from the pid is then simply a matter of:

String name = map.get(pid);

You should probably use a domain class instead of a HashMap to hold that data. If you did that you could easily search a collection for a particular value.

public class Spot {
    private final String pid;
    private final String name;

    public Spot(String pid, String name) {
        this.pid = pid;
        this.name = name;
    }

    // getters 
}

You'll want to add override equals() and hashCode() also.

And then use a map instead of a list:

Map<String,Spot> spots = new HashMap<String,Spot>();
spots.put(pid, new Spot(pid, name));

Then to find one:

Spot spot = spots.get(pid);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM