Reputation: 151
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
Upvotes: 0
Views: 90
Reputation: 5451
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);
Upvotes: 1
Reputation: 328618
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);
Upvotes: 3