Current Problem : I've build a HashMap to save and retrieve some key and values. but i'm not sure how to retrieve all values by a specific name (String). At the moment it's printing all the values from the Hashmap and that's not the thing that i want to achieve.
In the example below i'm using the following fields
Fields
String name
// Object Example
The HashMap
Map<String,Example> mapOfExampleObjects = new HashMap<String,Example>();
The for loop to retrieve the values from the hashmap by a certain key name
for(Map.Entry<String,Example> entry: mapOfExampleObjects.entrySet()){
if(mapOfExampleObjects.containsKey(name))
{
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
Current output
John + (Exampleobject)
Ian + (Exampleobject)
Ian + (Exampleobject)
Jalisha + (Exampleobject)
The Output that i want to achieve
Ian + (Exampleobject)
Ian + (Exampleobject)
Lars, your problem is this line:
if(mapOfExampleObjects.containsKey(name))
Your mapOfExampleObjects will always contain the key 'Ian' every time you go through the loop. What you want is more like:
if( name.equals(entry.getKey()) )
You can extract the keySet
of the map and manipulate it to select the entries you want:
class Example {
final String name;
Example(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public void test() {
// Sample data.
Map<String, Example> mapOfExampleObjects = new HashMap<String, Example>();
mapOfExampleObjects.put("John", new Example("John Smith"));
mapOfExampleObjects.put("Ian", new Example("Ian Bloggs"));
mapOfExampleObjects.put("Ian", new Example("Ian Smith"));
mapOfExampleObjects.put("Jalisha", new Example("Jalisha Q"));
// Using a Set you can extract many.
Set<String> want = new HashSet<String>(Arrays.asList("Ian"));
// Do the extract - Just keep the ones I want.
Set<String> found = mapOfExampleObjects.keySet();
found.retainAll(want);
// Print them.
for (String s : found) {
System.out.println(mapOfExampleObjects.get(s));
}
}
Note that this will still only print one Ian
because a Map
retains only one value against each key. You will need to use a different structure (perhaps Map<String,List<Example>>
) to retain multiple values against each key.
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.