Map<String, String> to TreeMap<Integer, String> [duplicate] - java

This question already has answers here:
How to convert Map<String, String> to Map<Long, String> ? (option : using guava)
(6 answers)
Closed 4 years ago.
I have a Map<String, String> object. I want to have it sorted by the keys, but the keys should be seen as integer. I just created an TreeMap<Integer, String>(myMapObject).
But this obviously does not work. How can I create a new TreeMap and change the keys from String to Integer?

You can use Collectors.toMap in Java 8:
Map<Integer, String> map1 = map.entrySet().stream().collect(Collectors.toMap(entry -> Integer.parseInt(entry.getKey()), Map.Entry::getValue, (a, b) -> b));
Or below traditional approach:
Map<Integer, String> map1 = new HashMap<>();
for(final Map.Entry<String, String> entry : map.entrySet()){
map1.put(Integer.parseInt(entry.getKey()), entry.getValue());
}

Related

merge two Map Values in Java and if key is same append the Values not overwrite in Java 7 or Java 8 [duplicate]

This question already has answers here:
Merge two maps with Java 8
(5 answers)
How can I combine two HashMap objects containing the same types?
(17 answers)
Closed 2 years ago.
I want to merge 2 Maps, but when the key is the same, the values should be appended instead of overwritten.
Let's say
Map<String, Set<String>> map1 = new HashMap<>();
Set<String> set1 = new HashSet<>();
set1.add("AB");
set1.add("BC");
map1.put("ABCD",set1);
Map<String, Set<String>> map2 = new HashMap<>();
Set<String> set2 =new HashSet<>();
set2.add("CD");
set2.add("EF");
map2.put("ABCD",set2);
map1.putAll(map2);
So here the key is same.I know putAll will overwrite the values if key is same
But I am looking for an output like
{ABCD=[AB,BC,CD,ED]}
If someone can help me to resolve, will be so thankful.
You can concat two maps using Stream.concat then collect using groupingBy map key and value as Set.
Map<String, Set<String>> res =
Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.groupingBy(e-> e.getKey(),
Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toSet())));
Note: Solution use Java 9+ flatMapping
Or
You can use merge function of map. Here merge map2 data into map1
map2.forEach((key, val) -> map1.merge(key, val, (a, b) -> {a.addAll(b); return a;}));
Output: {ABCD=[AB, BC, CD, EF]}
You make use of the merging function provided to Collectors.toMap that specifies what to do with values of duplicate keys with Streams. Demo
final Map<String, Set<String>> map3 = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> Stream.concat(a.stream(), b.stream()).collect(Collectors.toSet())));
You can apply a similar approach using Map#merge. Demo
final Map<String, Set<String>> map3 = new HashMap<>(map1);
map2.forEach((key, val) -> map3.merge(key, val,
(a, b) -> Stream.concat(a.stream(), b.stream()).collect(Collectors.toSet())));
You can use Stream API to merge the values of the same keys, Check if the map2 has the same keys from map1 and loop over them and merge the values together using addAll()
map1.entrySet().stream().filter(entry -> map2.containsKey(entry.getKey()))
.forEach(entry -> entry.getValue().addAll(map2.get(entry.getKey())));
, main function
public static void main(String[] args) {
Map<String, Set<String>> map1 = new HashMap<>();
Set<String> set1 = new HashSet<>();
set1.add("AB");
set1.add("BC");
map1.put("ABCD", set1);
Map<String, Set<String>> map2 = new HashMap<>();
Set<String> set2 = new HashSet<>();
set2.add("CD");
set2.add("EF");
map2.put("ABCD", set2);
map1.entrySet()
.stream()
.filter(entry -> map2.containsKey(entry.getKey()))
.forEach(entry -> entry.getValue().addAll(map2.get(entry.getKey())));
System.out.println(map1);
}
, output
{ABCD=[AB, BC, CD, EF]}

What order does a HashMap follow in Java? [duplicate]

This question already has answers here:
Difference between HashMap, LinkedHashMap and TreeMap
(17 answers)
Closed 3 years ago.
import java.util.*;
// import java.io.*;
class test {
public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<Integer, String> map2 = new HashMap<Integer, String>();
map1.put("Code", 1);
map1.put("Amit", 2);
map1.put("Better", 4);
map1.put("Coding", 5);
map2.put(1, "Test");
map2.put(2, "Kumar");
map2.put(3, "Ghai");
map2.put(4, "Coding");
test t = new test();
t.HashMapCQ2(map1, map2);
}
public void HashMapCQ2(HashMap<String, Integer> map1, HashMap<Integer, String> map2) {
HashMap<String, String> out = new HashMap<String, String>();
for (String str : map1.keySet())
if (map2.containsKey(map1.get(str)))
out.put(str, map2.get(map1.get(str)));
System.out.println(out);
}
}
The expected order would be {Code=Test, Amit=Kumar, Better=Coding}
But I am getting {Better=Coding, Amit=Kumar, Code=Test}.
Does HashMap order the list according to some criteria?
HashMaps in Java are not ordered. There are alternative Maps which preserve the order. Have a look at the following question, which already has answers:
Java Ordered Map

Java 8: Transform EnumMap<ExampleEnum, String> to Map<String, Object>

I have a situation where I need to copy my EnumMap<ExampleEnum,String> to Map<String, Object>. Many examples on Stack Overflow shows how to cast from one data type to another but not from enum. I have tried doing it through stream but no luck. Here is my code
private enum Number{
One, Two, Three;
}
final Map<Number, String> map = Collections.synchronizedMap(new EnumMap<Number, String> (Number.class));
populateMap(map);
Map<String, Object> newMap= new HashMap<String, Object>();
Now I want to do something like
newMap.putAll(map);
How can I do it through Stream APIs?
A more concise answer is,
final Map<Number, String> map = Collections.synchronizedMap(new EnumMap<>(Number.class));
Map<String, Object> newMap= new HashMap<>();
map.forEach((key, value) -> newMap.put(key.name(), value));
Map<String, Object> newMap = map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue));

How to map values in a map in Java 8? [duplicate]

This question already has answers here:
Using streams, how can I map the values in a HashMap?
(4 answers)
Closed 8 years ago.
Say I have a Map<String, Integer>. Is there an easy way to get a Map<String, String> from it?
By easy, I mean not like this:
Map<String, String> mapped = new HashMap<>();
for(String key : originalMap.keySet()) {
mapped.put(key, originalMap.get(key).toString());
}
But rather some one liner like:
Map<String, String> mapped = originalMap.mapValues(v -> v.toString());
But obviously there is no method mapValues.
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()));
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.

How merge list when combine two hashMap objects in Java [duplicate]

This question already has answers here:
How can I combine two HashMap objects containing the same types?
(17 answers)
Closed 9 years ago.
I have two HashMaps defined like so:
HashMap<String, List<Incident>> map1 = new HashMap<String, List<Incident>>();
HashMap<String, List<Incident>> map2 = new HashMap<String, List<Incident>>();
Also, I have a 3rd HashMap Object:
HashMap<String, List<Incident>> map3;
and the merge list when combine both.
In short, you can't. map3 doesn't have the correct types to merge map1 and map2 into it.
However if it was also a HashMap<String, List<Incident>>. You could use the putAll method.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
map3.putAll(map2);
If you wanted to merge the lists inside the HashMap. You could instead do this.
map3 = new HashMap<String, List<Incident>>();
map3.putAll(map1);
for(String key : map2.keySet()) {
List<Incident> list2 = map2.get(key);
List<Incident> list3 = map3.get(key);
if(list3 != null) {
list3.addAll(list2);
} else {
map3.put(key,list2);
}
}
create third map and use putAll() method to add data from ma
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
You have different type in question for map3 if that is not by mistake then you need to iterate through both map using EntrySet
Use commons collections:
Map<String, List<Incident>> combined = CollectionUtils.union(map1, map2);
If you want an Integer map, I suppose you could apply the .hashCode method to all values in your Map.
HashMap has a putAll method.
Refer this :
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

Categories

Resources