You need to stream the entries and collect them in a new map:
Map<String, String> result = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()));
Answer from assylias on Stack OverflowYou need to stream the entries and collect them in a new map:
Map<String, String> result = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()));
The easiest way to do so is:
Map<String, Integer> map = new HashMap<>();
Map<String, String> mapped = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
What you do here, is:
- Obtain a
Stream<Map.Entry<String, Integer>> - Collect the results in the resulting map:
- Map the entries to their key.
- Map the entries to the new values, incorporating
String.valueOf.
The reason you cannot do it in a one-liner, is because the Map interface does not offer such, the closest you can get to that is map.replaceAll, but that method dictates that the type should remain the same.
To get all the values from a map:
for (Tab tab : hash.values()) {
// do something with tab
}
To get all the entries from a map:
for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}
Java 8 update:
To process all values:
hash.values().forEach(tab -> /* do something with tab */);
To process all entries:
hash.forEach((key, tab) -> /* do something with key and tab */);
Map is internally made up of Map.Entry objects. Each Entry contains key and value. To get key and value from the entry you use accessor and modifier methods.
If you want to get values with given key, use get() method and to insert value, use put() method.
#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)
map.get("Germany") // returns 4
If you want to get the set of keys from map, you can use keySet() method
Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
System.out.println(key + ": " + map.get(key));
}
Generally, To get all keys and values from the map, you have to follow the sequence in the following order:
- Convert
HashmaptoMapSetto get set of entries inMapwithentryset()method.:
Set st = map.entrySet(); - Get the iterator of this set:
Iterator it = st.iterator(); - Get
Map.Entryfrom the iterator:Map.Entry entry = it.next(); - use
getKey()andgetValue()methods of theMap.Entryto get keys and values.
// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
Map.Entry entry = mapIterator.next();
System.out.print(entry.getKey() + " : " + entry.getValue());
}
In short, use iterator directly in for
for(Map.Entry entry:map.entrySet()){
System.out.print(entry.getKey() + " : " + entry.getValue());
}