I need to invert map which is <String, List<String>> to Map<String,String> using java 8. with assumption that the values are unique. For example,
Input Map -
{"Fruit" -> ["apple","orange"], "Animal" -> ["Dog","Cat"]}
Output Map
{"apple" -> "Fruit", "orange" -> "Fruit", "Dog"->"Animal", "Cat" -> "Animal"}
Map <String, String> outputMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : inputMap.entrySet()) {
entry.getValue().forEach(value -> outputMap.put(value, entry.getKey()));
}
Is this right? can we achieve this using streams java 8?
You an try this way
Map <String, String> updatedMap = new HashMap<>();
oldMap.keySet()
.forEach(i -> oldMap.get(i)
.forEach(k -> updatedMap.put(k, i)));
Do like this :
public class InverterMap {
public static void main(String[] args) {
Map<String, List<String>> mp = new HashMap<String, List<String>>();
mp.put("Fruit", Arrays.asList("Apple", "Orange"));
mp.put("Animal", Arrays.asList("Dog", "Cat"));
System.out.println(mp); // It returned {Fruit=[Apple, Orange], Animal=[Dog, Cat]}
Map<String, String> invertMap = mp.entrySet().stream().collect(HashMap::new,
(m, v) -> v.getValue().forEach(k -> m.put(k, v.getKey())), Map::putAll);
System.out.println(invertMap);// It returned {Apple=Fruit, Cat=Animal, Orange=Fruit, Dog=Animal}
}
}
Read Stream.collect(Supplier supplier, BiConsumer, BiConsumer combiner) for more info.
Related
I want to convert:
Map<String, Map<String, List<Map<String, String>>>> inputMap
to:
Map<String, Map<String, CustomObject>> customMap
inputMap is provided in the config and is ready but I need to customMap Format. CustomObject will be derived from List<Map<String, String>> using few lines of code in a function.
I have tried a normal way of iterating input map and copying key values in customMap. Is there any efficient way of doing that using Java 8 or some other shortcut?
Map<String, Map<String, List<Map<String, String>>>> configuredMap = new HashMap<>();
Map<String, Map<String, CustomObj>> finalMap = new HashMap<>();
for (Map.Entry<String, Map<String, List<Map<String, String>>>> attributeEntry : configuredMap.entrySet()) {
Map<String, CustomObj> innerMap = new HashMap<>();
for (Map.Entry<String, List<Map<String, String>>> valueEntry : attributeEntry.getValue().entrySet()) {
innerMap.put(valueEntry.getKey(), getCustomeObj(valueEntry.getValue()));
}
finalMap.put(attributeEntry.getKey(), innerMap);
}
private CustomObj getCustomeObj(List<Map<String, String>> list) {
return new CustomObj();
}
One solution is to stream the entrySet of inputMap, and then use Collectors#toMap twice (once for the outer Map, and once for the inner Map):
Map<String, Map<String, CustomObj>> customMap = inputMap.entrySet()
.stream()
.collect(Collectors.toMap(Function.identity(), entry -> {
return entry.getValue()
.entrySet()
.stream()
.collect(Collectors.toMap(Function.identity(),
entry -> getCustomeObj(entry.getValue())));
}));
You could stream, but that ain't going to look readable; at least to me. So if you have a method:
static CustomObject fun(List<Map<String, String>> in) {
return .... // whatever processing you have here
}
you could still use the java-8 syntax, but in a different form:
Map<String, Map<String, CustomObject>> customMap = new HashMap<>();
inputMap.forEach((key, value) -> {
value.forEach((innerKey, listOfMaps) -> {
Map<String, CustomObject> innerMap = new HashMap<>();
innerMap.put(innerKey, fun(listOfMaps));
customMap.put(key, innerMap);
});
});
If you can make the inner map immutable, you could make that even shorter:
inputMap.forEach((key, value) -> {
value.forEach((innerKey, listOfMaps) -> {
customMap.put(key, Collections.singletonMap(innerKey, fun(listOfMaps)));
});
});
IMHO streaming is not so bad idea. There're no bad tools. It depends on how you're using them.
In this particular case I would extract the repeating pattern into an utility method:
public static <K, V1, V2> Map<K, V2> transformValues(Map<K, V1> map, Function<V1, V2> transformer) {
return map.entrySet()
.stream()
.collect(toMap(Entry::getKey, e -> transformer.apply(e.getValue())));
}
The method above can be implemented using any approach, though I think Stream API fits pretty well here.
Once you defined the utility method, it can be used as simple as follows:
Map<String, Map<String, CustomObj>> customMap =
transformValues(inputMap, attr -> transformValues(attr, this::getCustomObj));
The actual transformation is effectively one liner. So with proper JavaDoc for transformValues method the result code is pretty readable and maintainable.
How about Collectors.toMap for the entries both at an outer and inner level such as:
Map<String, Map<String, CustomObj>> finalMap = configuredMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
attributeEntry -> attributeEntry.getValue().entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
valueEntry -> getCustomeObj(valueEntry.getValue())))));
I'm trying to do the following modification:
final Map<String, List<Map<String, String>>> scopes = scopeService.fetchAndCacheScopesDetails();
final Map<String, Map<String, String>> scopesResponse = scopes.entrySet().stream().collect
(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
.stream().collect(Collectors.toMap(s -> (String) s.get(SCOPE_NM), s -> (String) s.get(SCOPE_ID))))
);
But I face "Duplicate key" error, so I'd like to change scopeResponses to Map<String, Map<String, List<String>>>
Could you tell me how to merge values s -> (String) s.get(SCOPE_ID) into a List or Set in this situation?
You need to create a Set for the value of the inner Map, and supply a merge function:
final Map<String, Map<String, Set<String>>> scopesResponse = scopes.entrySet().stream().collect
(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
.stream().collect(Collectors.toMap(s -> s.get(SCOPE_NM),
s -> {Set<String> set= new HashSet<>(); set.add(s.get(SCOPE_ID)); return set;},
(s1,s2)->{s1.addAll(s2);return s1;}))));
Or, you can construct the inner Map with groupingBy:
final Map<String, Map<String, Set<String>>> scopesResponse2 = scopes.entrySet().stream().collect
(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
.stream().collect(Collectors.groupingBy(s -> s.get(SCOPE_NM),
Collectors.mapping(s -> s.get(SCOPE_ID),Collectors.toSet())))));
You can also do it using Guava's ListMultimap (multimap is like a map of lists):
Map<String, ListMultimap<String, String>> scopesResponse = scopes.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> toMultimap(e)));
where
static ImmutableListMultimap<String, String> toMultimap(
Map.Entry<String, List<Map<String, String>>> entry) {
return entry.getValue().stream().collect(ImmutableListMultimap.toImmutableListMultimap(
s -> (String) s.get(SCOPE_NM),
s -> (String) s.get(SCOPE_ID)
));
}
If the values in the lists turn out to be duplicated, and you don't want that, use SetMultimap instead.
How would you use Java 8 streams to swap keys in this map of maps? Or at least clean up this mess a little bit...
Map<Type1, Map<Type2, String>> to Map<Type2, Map<Type1, String>>
Using nested for loops (untested):
Map<Type1, Map<Type2, String>> map ...
Map<Type2, Map<Type1, String>> map2 = new HashMap<>();
for (Type 1 type1 : map.keySet()) {
for(Entry<Type2, String> entry : map.get(type1)) {
if (map2.get(entry.key() == null) {
map2.push(entry.key(), new HashMap<Type1, String>();
}
map2.get(entry.key()).put(type1, entry.value();
}
}
So far I think you would need to flap map into all unique combinations of Type1, Type2, and String and store this set in some sort of intermediate collection.
Definitely wrong:
map.entrySet().stream().flatMap(t -> <Type1, Type2,
String>).collect(Collectors.toMap(t -> t.Type2, Collectors.toMap(t ->
t.type1, t->t.String))
Streams aren't well-suited for this type of problem. Instead, consider using other java 8 additions -- Map#forEach and Map#computeIfAbsent:
map.forEach( (t1, e) ->
e.forEach( (t2, v) ->
result.computeIfAbsent(t2, x -> new HashMap<>()).put(t1, v)
)
);
Misha already showed you the straight forward solution. If you really want to use Streams it could look like this:
public static <S, T> Map<T, Map<S, String>> convertStream(Map<S, Map<T, String>> map) {
return map.entrySet().stream().flatMap(m1 -> m1.getValue().entrySet()
.stream().map(e -> new Object() {
final T outer = e.getKey();
final Map<S, String> map;
{
map = new HashMap<>();
map.put(m1.getKey(), e.getValue());
}
})).collect(Collectors.toMap(o -> o.outer, o -> o.map, (m1, m2) -> {
m1.putAll(m2);
return m1;
}));
}
Map<Type2, Map<Type1, Object>> finalAnswer = map.entrySet().stream()
.collect(()->new HashMap<Type2,Map<Type1,Object>>(),
(mapAccumulator, left)->{
for(Entry<?, ?> leftEntry : left.getValue().entrySet() ){
Map<Type1,Object> tempMap = new HashMap<>();
tempMap.put(left.getKey(), leftEntry.getValue());
mapAccumulator.put((Type2) leftEntry.getKey(), tempMap);
}
/*accumulator*/},
(mapLeft,mapRight)->{mapLeft.putAll(mapRight); /*combiner*/});
map.entrySet().forEach(System.out::println);
I have Map<String, Object> which has to be become Map<String, String>. Filtering should be done by List<String>.
That list contains keys of map elements that should be in new map.
For this I need to use streams.
Map<String, Object> oldMap;
List<String> keysForFiltering;
Map<String, String> newMap;
It would be more efficient if the filter would operate on a Set of keys instead of a List of keys, since searching a Set is more efficient than searching a List.
Map<String, String> newMap =
oldMap.entrySet()
.stream()
.filter(e -> keysForFiltering.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().toString()));
since you have a map then you can get the stream of that and use a custom predicate, that predicate need to check if the Entry.key is present in your list or not
Map<String, String> myMap = new HashMap<>();
myMap.put("A", "fortran");
myMap.put("B", "java");
myMap.put("C", "c++");
myMap.put("D", "php");
List<String> keysForFiltering = Arrays.asList("A", "C");
Predicate<Entry<String, String>> myPredicate = t -> keysForFiltering.contains(t.getKey());
Map<String, String> filteredMap = myMap
.entrySet().stream().filter(myPredicate)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
System.out.println(filteredMap);
I want to be able to convert a List to a HashMap where the key is the elementName and the values is a list of something random (in this case its the Element Name). So in short I want (A->List(A), B->List(B), C-> List(C)). I tried using toMap() and passing it the keyMapper and ValueMapper but I get a compilation error. I would really appreciate if someone can help me out.
Thanks!
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = Arrays.asList("A","B","C","D");
Map<String, List<String>> map = list.stream().map((element)->{
Map<String, List<String>> map = new HashMap<>();
map.put(element, Arrays.asList(element));
return map;
}).collect(??);
}
Function<Map<String, String>, String> key = (map) -> {
return map.keySet().stream().findFirst().get();
};
Function<Map<String, String>, String> value = (map) -> {
return map.values().stream().findFirst().get();
};
=== This worked for me
Thanks for all the help guys! #izstas "they should operate on the elements" helped a lot :). Actually this is what I was looking for to be exact
public static void test2 (){
Function<Entry<String, List<String>>, String> key = (entry) -> {
return entry.getKey();
};
Function<Entry<String, List<String>>, List<String>> value = (entry) -> {
return new ArrayList<String>(entry.getValue());
};
BinaryOperator<List<String>> merge = (old, latest)->{
old.addAll(latest);
return old;
};
Map<String, List<String>> map1 = new HashMap<>();
map1.put("A", Arrays.asList("A1", "A2"));
map1.put("B", Arrays.asList("B1"));
map1.put("D", Arrays.asList("D1"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("C", Arrays.asList("C1","C2"));
map2.put("D", Arrays.asList("D2"));
Stream<Map<String, List<String>>> stream =Stream.of(map1, map2);
System.out.println(stream.flatMap((map)->{
return map.entrySet().stream();
}).collect(Collectors.toMap(key, value, merge)));
}
You can use the groupingBy method to manage aggregation, for example:
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D", "A");
Map<String, List<String>> map = list.stream().collect(Collectors.groupingBy(Function.identity()));
}
If you want more flexibility (for example to map the value and return a Set instead of a List) you can always use the groupingBy method with more parameters as specified in javadoc:
Map<City, Set<String>> namesByCity = people.stream().collect(Collectors.groupingBy(Person::getCity, mapping(Person::getLastName, toSet())));
Functions key and value you have defined in your code are not correct because they should operate on the elements of your list, and your elements are not Maps.
The following code works for me:
List<String> list = Arrays.asList("A", "B", "C", "D");
Map<String, List<String>> map = list.stream()
.collect(Collectors.toMap(Function.identity(), Arrays::asList));
First argument to Collectors.toMap defines how to make a key from the list element (leaving it as is), second argument defines how to make a value (making an ArrayList with a single element).
Thanks for all the help guys! #izstas "they should operate on the elements" helped a lot :). Actually this is what I was looking for to be exact
public static void test2 (){
Function<Entry<String, List<String>>, String> key = (entry) -> {
return entry.getKey();
};
Function<Entry<String, List<String>>, List<String>> value = (entry) -> {
return new ArrayList<String>(entry.getValue());
};
BinaryOperator<List<String>> merge = (old, latest)->{
old.addAll(latest);
return old;
};
Map<String, List<String>> map1 = new HashMap<>();
map1.put("A", Arrays.asList("A1", "A2"));
map1.put("B", Arrays.asList("B1"));
map1.put("D", Arrays.asList("D1"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("C", Arrays.asList("C1","C2"));
map2.put("D", Arrays.asList("D2"));
Stream<Map<String, List<String>>> stream =Stream.of(map1, map2);
System.out.println(stream.flatMap((map)->{
return map.entrySet().stream();
}).collect(Collectors.toMap(key, value, merge)));
}