Group the map values to avoid duplicate [duplicate] - java

This question already has answers here:
Reverse HashMap keys and values in Java
(12 answers)
Closed 5 years ago.
I have a Map(map1) whose key is another map(map2) and value is string.
The value of map1 has several duplicate, so I must group them and set as key in another map3 whose value has to be map2.
eg:
map1 { [[a,b],xyz], [[c,d],wrt] , [[e,f],xyz] , [[r,m],xyz] }
output should be :
map3 { [ xyz,[ [a,b],[e,f],[r,m] ] ] , [ wrt,[ [c,d] ]
can i obtain like this ?

try MultiValueMap from (commons-collections) library
Map map1 = new HashMap<String[], String>();
map1.put(new String[]{"a", "b"}, "xyz");
map1.put(new String[]{"c", "d"}, "wrt");
map1.put(new String[]{"e", "f"}, "xyz");
map1.put(new String[]{"c", "d"}, "xyz");
MultiValueMap map2 = new MultiValueMap();
for(String[] key: map1.keySet()) {
String value = map1.get(key);
map2.add(value, key);
}
// now you got map2 as you want

NO, Though you can declare it but while using it, it may allow same keys(human readable). Because Map do not override Object's equals method your key comparison will be on JVM's object level (it may be different for objects with same values in them).

You can use the stream API to solve it:
Map<String, List<Map<String, String>>> map3 = map.entrySet().stream()
.collect(Collectors.groupingBy(Entry::getValue,
Collectors.mapping(Entry::getKey,
Collectors.toList())));
Explanation:
The entries will be grouped by its values (groupingBy(Entry::getValue).
But the values should not be a list of entries so the downstream is necessary. This is the list of keys of the original map.

It is not clear from your post what do you mean by map2, but let's assume you would like to use each Map.Entry<String, String> entry from map2 for each key for map1.
The following code is Java 7, it's a bit verbose. It could be done shorter with Java 8 streams, I guess.
public class MapReverser {
private Map<Map.Entry<String, String>, String> map1 = new HashMap<>();
private Map<String, String> map2 = new LinkedHashMap<>();
private void prepareMaps() {
map2.put("a", "b");
map2.put("c", "d");
map2.put("e", "f");
map2.put("r", "m");
String[] valueArray = { "xyz", "wrt", "xyz", "xyz" };
int i = 0;
for (Map.Entry<String, String> entry : map2.entrySet()) {
map1.put(entry, valueArray[i]);
i++;
}
}
public Map<String, List<Map.Entry<String, String>>> reverse() {
Map<String, List<Map.Entry<String, String>>> reversedMap = new HashMap<>();
for (Map.Entry<Map.Entry<String, String>, String> entry : map1.entrySet()) {
List<Map.Entry<String, String>> reversedMapValue = reversedMap.get(entry.getValue());
if (reversedMapValue == null) {
reversedMapValue = new ArrayList<>();
}
reversedMapValue.add(entry.getKey());
reversedMap.put(entry.getValue(), reversedMapValue);
}
return reversedMap;
}
private void printResult(Map<String, List<Map.Entry<String, String>>> reversedMap) {
for (Map.Entry<String, List<Map.Entry<String, String>>> entry : reversedMap.entrySet()) {
System.out.println("Key: \n" + entry.getKey());
System.out.println("Values:");
List<Map.Entry<String, String>> valuesList = entry.getValue();
for (Map.Entry<String, String> value : valuesList) {
System.out.println(value );
}
System.out.println("\n");
}
}
public static void main(String[] args) {
MapReverser mapReverser = new MapReverser();
mapReverser.prepareMaps();
Map<String, List<Map.Entry<String, String>>> reversedMap = mapReverser.reverse();
mapReverser.printResult(reversedMap);
}
}

Related

How to delete duplicates values from HashMap<Integer, ArrayList<Integer>>? [duplicate]

I have a map with duplicate values:
("A", "1");
("B", "2");
("C", "2");
("D", "3");
("E", "3");
I would like to the map to have
("A", "1");
("B", "2");
("D", "3");
Do you know how to get rid of the duplicate values?
At present, I get 'java.util.ConcurrentModificationException' error.
Thank you.
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
Set<String> keys = map.keySet(); // The set of keys in the map.
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
System.out.println(key + "\t" + value);
String nextValue = map.get(key);
if (value.equals(nextValue)) {
map.remove(key);
}
}
System.out.println(map);
}
make a reverse HashMap!
HashMap<String, String> map = new HashMap<String, String>();
Set<String> keys = map.keySet(); // The set of keys in the map.
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = map.get(key);
map.put(value, key);
}
now that you have the hashMap you need reverse it or print it.
in anyway do not delete while iterating hashMap. save the values in a list and delete them in an outer loop
Assuming that you use Java 8, it could be done using the Stream API with a Set<String> that will store the existing values:
Map<String, String> map = new HashMap<>();
map.put("A", "1");
...
System.out.printf("Before: %s%n", map);
// Set in which we keep the existing values
Set<String> existing = new HashSet<>();
map = map.entrySet()
.stream()
.filter(entry -> existing.add(entry.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.printf("After: %s%n", map);
Output:
Before: {A=1, B=2, C=2, D=3, E=3}
After: {A=1, B=2, D=3}
NB: Strictly speaking a predicate of a filter is not supposed to be stateful, it should be stateless as mentioned into the javadoc in order to ensure that the result remain deterministic and correct even if we use a parallel stream. However here, I assume that you don't intend to use a parallel stream such that this approach remains valid.
Map<String,Object> mapValues = new HashMap<String,Object>(5);
mapValues.put("1", "TJ");
mapValues.put("2", "Arun");
mapValues.put("3", "TJ");
mapValues.put("4", "Venkat");
mapValues.put("5", "Arun");
Collection<Object> list = mapValues.values();
for(Iterator<Object> itr = list.iterator(); itr.hasNext();)
{
if(Collections.frequency(list, itr.next())>1)
{
itr.remove();
}
}
ConcurrentModificationException happening,because you are removing from map
if (value.equals(nextValue)) {
map.remove(key);
}
You have to remove from iterator
if (value.equals(nextValue)) {
keyIter.remove(key);
}
Coming to the duplicate entry issue,Its pretty simple :Find duplicate values in Java Map?
This can be done using Java 8. The concept of stream is required. The pseudocode,
is stream().filter().collect().
If the Initial Map : {A=1, B=2, C=2, D=3, E=3}. Then the required answer after removing the duplicates is {A=1, B=2, D=3} .
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class RemoveDuplicates1 {
public static void main(String[] args) {
//Initial Map : {A=1, B=2, C=2, D=3, E=3}
//After => {A=1, B=2, D=3}
Map<String , String > map = new HashMap<>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
System.out.printf("before : " +map );
System.out.println("\n");
Set<String> set = new HashSet<>();
map = map.entrySet().stream()
.filter(entry -> set.add(entry.getValue()))
.collect(Collectors.toMap(Map.Entry :: getKey , Map.Entry :: getValue));
System.out.printf("after => " + map);
}
}
If this is yours frequent requirement then DualHashBidiMap calss of apache's commons.collections will help you more instead of using HashMap.
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
System.out.println("Initial Map : " + map);
for (String s : new ConcurrentHashMap<>(map).keySet()) {
String value = map.get(s);
for (Map.Entry<String, String> ss : new ConcurrentHashMap<>(map)
.entrySet()) {
if (s != ss.getKey() && value == ss.getValue()) {
map.remove(ss.getKey());
}
}
}
System.out.println("Final Map : " + map);
}
This can be easily done by putting your hashmap into arraylist.
This arraylist is of hashmap type.
ArrayList<HashMap<String, String>> mArrayList=new ArrayList<>();
HashMap<String, String> map=new HashMap<>();
map.put("1", "1");
mArrayList.add(map);
map=new HashMap<>();
map.put("1", "1");
mArrayList.add(map);
map=new HashMap<>();
map.put("1", "2");
mArrayList.add(map);
map=new HashMap<>();
map.put("1", "3");
mArrayList.add(map);
map=new HashMap<>();
map.put("1", "2");
mArrayList.add(map);
for(int i=0;i<mArrayList.size();i++)
{
temp=mArrayList.get(i).get("1");
for(int k=i+1;k<mArrayList.size();k++)
{
if(temp.equals(mArrayList.get(k).get("1")))
{
mArrayList.remove(k);
}
}
}
Now print your arraylist...all the duplicate values from the hashmap easily removed...This is the easiest way to remove duplicacy
This will be helpful to remove duplicate values from map.
Map<String, String> myMap = new TreeMap<String, String>();
myMap.put("1", "One");
myMap.put("2", "Two");
myMap.put("3", "One");
myMap.put("4", "Three");
myMap.put("5", "Two");
myMap.put("6", "Three");
Set<String> mySet = new HashSet<String>();
for (Iterator itr = myMap.entrySet().iterator(); itr.hasNext();)
{
Map.Entry<String, String> entrySet = (Map.Entry) itr.next();
String value = entrySet.getValue();
if (!mySet.add(value))
{
itr.remove();
}
}
System.out.println("mymap :" + mymap);
Output:
mymap :{1=One, 2=Two, 4=Three}
If you are looking just to remove the concurrentModification exception, then just replace your HashMap with ConcurrentHashMap.
To know more about ConcurrentHashMap look here
It can be done without mutating the original map:
public static <K,V> Map<K,V> getDistinctValues(Map<K,V> map) {
Set<V> values = new HashSet<>();
return map.entrySet().stream()
.filter(entry -> values.add(entry.getValue()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
}

Is there any simple way to merge value set when we convert key of map to lower case in Java?

I have a map with mixed cases, e.g.
{a=[v1, V1], A={v2, V2, v3}
I'd like to make everything to lowerCase,
{a=[v1, v2, v3]}
I did it verbosely in Java, wondering whether is any simple/better way. Thanks
Map<String, Set<String>> result = new HashMap<>();
for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
String key = entry.getKey().toLowerCase();
Set<String> currSet = entry.getValue().stream().map(v -> v.toLowerCase()).collect(Collectors.toSet());
Set<String> existSet = result.get(key);
if (existSet == null) {
result.put(key, currSet);
} else {
existSet.addAll(currSet);
}
}
You could utilize putIfAbsent(), or computeIfAbsent() to prevent an unnecessary instantiation of a set, on the map to create a new set if there isn't a value yet, and then just call addAll()
Map<String, Set<String>> result = new HashMap<>();
for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
String key = entry.getKey().toLowerCase();
Set<String> currSet = entry.getValue().stream().map(v -> v.toLowerCase()).collect(Collectors.toSet());
result.computeIfAbsent(key, k -> new HashSet<>()).addAll(currSet);
}
putIfAbsent() is similar, but again, it will always instantiate a new HashSet instead of only instantiating one if the value is actually absent:
result.putIfAbsent(key, new HashSet<>()).addAll(currSet);
In case you are a java-stream fan:
#Test
void mapToMap() {
// Map.of: Java 9 or higher
Map<String, Set<String>> before = Map.of("A", Set.of("A", "a"), "a", Set.of("b", "B", "c"));
// Collectors.toMap: Java 8 or higher
Map<String, Set<String>> after = before.entrySet().stream().collect(
Collectors.toMap(
e -> e.getKey().toLowerCase(),
e -> e.getValue().stream().map(String::toLowerCase).collect(Collectors.toSet()),
(existing, replacement) -> {
existing.addAll(replacement);
return existing;
}
)
);
assertThat(after.size()).isEqualTo(1);
assertThat(after.get("a")).containsExactly("a", "b", "c");
}
You can use Map.computeIfAbsent() like this.
public static void main(String[] args) throws IOException {
Map<String, Set<String>> input = Map.of(
"a", Set.of("v1", "V1"),
"A", Set.of("v2", "V2", "v3"));
Map<String, Set<String>> output = new LinkedHashMap<>();
for (Entry<String, Set<String>> e : input.entrySet())
output.computeIfAbsent(e.getKey().toLowerCase(), k -> new HashSet<>())
.addAll(e.getValue().stream().map(String::toLowerCase).toList());
System.out.println(output);
}
output:
{a=[v1, v2, v3]}

Invert Map | Values ---> Keys

I want to be able to inverse a given HashMap that has multiple keys can point to the same value.
HashMap<String, String> cities = new HashMap<String, String>();
cities.put("Manchester", "UK");
cities.put("London", "UK");
static HashMap<String, String> inverseMap(HashMap map) {
// something that has "UK" point to both "Manchester" and "London"
// if it can be done without using any special Java 8 feature, that would be great
}
I am unsure where to start.
Do it like this. Basically, it employs a merge function which concatenates values for a duplicate key.
Create a new map
Use the values of the old map for the keys to the new
If the new map does not have a value for the key, put the value in the new map
Otherwise, concatenate the value to the old value for that key
HashMap<String, String> cities = new HashMap<String, String>();
cities.put("Manchester", "UK");
cities.put("London", "UK");
cities.put("New York", "US");
cities.put("Chicago", "US");
Map<String,String> inverted = new HashMap<>();
for (String key : cities.keySet()) {
String newKey = cities.get(key);
String value = inverted.get(newKey);
if (value == null) {
inverted.put(newKey, key);
} else {
value = value + ", " + key;
inverted.put(newKey, value);
}
}
for (Entry<String,String> e : inverted.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
It prints
UK -> Manchester, London
US -> New York, Chicago
Since you didn't specify how to handle duplicate keys. I could also have stored it in a Map<String,List<String>>
Is this what you're looking for?
Map<String, String> cities = new HashMap<>();
cities.put("Manchester", "UK");
cities.put("London", "UK");
Map<String, List<String>> reverseMap = new HashMap<>();
for (Entry<String, String> entry : cities.entrySet()) {
List<String> list = reverseMap.get(entry.getValue());
if (list == null) {
list = new ArrayList<>();
reverseMap.put(entry.getValue(), list);
}
list.add(entry.getKey());
}
System.out.println(reverseMap);
As multiple keys can contain the same value, you will have to be able to store multiple values per key in the inversed Map. I recommend using a Set as a value for this.
Create a map that can save a Set of Strings as values
Iterate through the original map
If the country is not found in the new map, create an entry there
Add the city to the map
This should also work with Java 7 without dependencies.
static HashMap<String, Set<String>> inverseMap(HashMap<String,String> map) {
HashMap<String,Set<String>> inversed=new HashMap<>();
for(Map.Entry<String,String> entry:map.entrySet()){
if(!inversed.containsKey(entry.getValue())){
inversed.put(entry.getValue(),new HashSet<>());
}
inversed.get(entry.getValue()).add(entry.getKey());
}
return inversed;
}
{Manchester=UK,London=UK} would turn into {UK={Manchester,London}} (order may differ).
You can look at MultiMap. It allows mapping of a single key to multiple values.
This is something has been implemented in both Google Guava
https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Multimap.html
ListMultimap<String, String> multimap = ArrayListMultimap.create();
for (President pres : US_PRESIDENTS_IN_ORDER) {
multimap.put(pres.firstName(), pres.lastName());
}
for (String firstName : multimap.keySet()) {
List<String> lastNames = multimap.get(firstName);
out.println(firstName + ": " + lastNames);
}
... produces output such as:
Zachary: [Taylor]
John: [Adams, Adams, Tyler, Kennedy] // Remember, Quincy!
George: [Washington, Bush, Bush]
Grover: [Cleveland, Cleveland] // Two, non-consecutive terms, rep'ing NJ!
As in Apache Commons Collections
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiValuedMap.html
MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();
map.put(key, "A");
map.put(key, "B");
map.put(key, "C");
Collection<String> coll = map.get(key);
coll will be a collection containing "A", "B", "C".
You can iterate over the entry set of your original map and use the values (country code) as key and add each key (cities) to a list:
static HashMap<String, List<String>> inverseMap(HashMap<String, String> map) {
HashMap<String, List<String>> countryToCity = new HashMap<>();
for(Map.Entry<String,String> entry: map.entrySet()){
countryToCity.computeIfAbsent(entry.getValue(), k -> new ArrayList<>()).add(entry.getKey());
}
return countryToCity;
}

How to sort a map of type Map<String, List<String>> in Java

Issue
I'm trying to sort a map Map>
which the map key set contain the order 1 2 3 4 ext ...
Code
The file which I'm retrieving data
filter.properties
1=gwtCacheControlFilter:com.palmyra.arch.presentation.port.server.GWTCacheControlFilter:true:/*:null:presentation
public Map<String, List<String>> initiateMapOfFilters() throws IOException {
Map<String, List<String>> filterMap = new HashMap<>();
Properties properties = new Properties();
properties.load(FilterFileStream);
for (Entry<Object, Object> filterFromFile : properties.entrySet()) {
String filterValue = filterFromFile.getValue().toString();
String[] split = filterValue.split(":");
ArrayList<String> list = new ArrayList<>();
for (String s : split) {
list.add(s);
}
//-------sort the list with order
filterMap.put(split[filterNameIndex], list);
}
// Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap); comment
return filterMap;
}
What I've tried
I want to return a map ordered by the key I tried:
Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap);
Thank you for any suggestion.
You have to use a comparator to make it work! Like this :
Map<Integer,String> unsortedMap = new Hashmap<Integer,String>();
Map<Integer,String> treeMap = new TreeMap<Integer,String>(
new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);//sort in descending order
}
});
Consider the below code. With java 8 you can use the Comparator.comparing method and get it done quite quickly.
TreeMap<String, List<String>> treeMap = new TreeMap<>(Comparator.comparing(t -> Integer.valueOf(t)));
treeMap.put("5", Arrays.asList(new String[] {"data1", "data2", "data3"}));
treeMap.put("3", Arrays.asList(new String[] {"data4", "data5", "data6"}));
treeMap.put("1", Arrays.asList(new String[] {"data7", "data8", "data9"}));
treeMap.put("4", Arrays.asList(new String[] {"data10", "data11", "data12"}));
treeMap.
forEach((k,v) -> System.out.println(k + "=="+v));
Output is sorted on basis of keys:
1==[data7, data8, data9]
3==[data4, data5, data6]
4==[data10, data11, data12]
5==[data1, data2, data3]

Best way to find element in List Java [duplicate]

It's a simple question,
I have a simple HashMap of which i want to reverse the keys and values.
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
myHashMap.put('a', "test one");
myHashMap.put('b', "test two");
and I want to create a new HashMap in which i put the opposites.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
e.g. Keys "test one" & "test two" and values 'a' & 'b'.
They all are unique, yes
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
myNewHashMap.put(entry.getValue(), entry.getKey());
}
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :
BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");
BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
As java-8 is out, you can also do it this way :
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, String> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:
Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();
Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique
org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
Sample code
HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap)
If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, List<String>> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
I wrote a simpler loop that works too (note that all my values are unique):
HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (char i : myHashMap.keySet()) {
reversedHashMap.put(myHashMap.get(i), i);
}
To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.
But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.
Iterate through the list of keys and values, then add them.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
reversedHashMap.put(myHashMap.get(key), key);
}
private <A, B> Map<B, A> invertMap(Map<A, B> map) {
Map<B, A> reverseMap = new HashMap<>();
for (Map.Entry<A, B> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
return reverseMap;
}
It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.
Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.
public static void main(String[] args) {
Map<String, String> test = new HashMap<String, String>();
test.put("a", "1");
test.put("d", "1");
test.put("b", "2");
test.put("c", "3");
test.put("d", "4");
test.put("d", "41");
System.out.println(test);
Map<String, String> test1 = MapUtils.invertMap(test);
System.out.println(test1);
Map<String, String> mapInversed =
test.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
System.out.println(mapInversed);
}
Output:
{a=1, b=2, c=3, d=41}
{1=a, 2=b, 3=c, 41=d}
{1=a, 2=b, 3=c, 41=d}
Use forEach introduced in Java 8
Map<Short, String> regularMap = new HashMap<>();
Map<String, Short> inversedMap = new HashMap<>();
regularMap.forEach((key, value) -> inversedMap.put(value, key));
for reverting the map, in your case:
private void reverseMap(Map<Character, String> map) {
Map<String, Character> newList = new HashMap<>();
map.forEach((key, value) -> newList.put(value, key));
System.out.println(newList);
}
or you can traverse the old hashmap
HashMap<String, Character> newList = new HashMap<String, Character>();
for (String key : list.keySet()){
newList.put(list.get(key), key);
}
For Reversing the Array of Dictionary. (If values are Unique)
private void reverseArrayMap(List<Map<String, String>> list) {
// reversing the array of dictionary
List<Map<String, String>> newList = new ArrayList<>();
Map<String, String> resDic = new HashMap<>();
for (Map<String, String> map : list) {
map.forEach((key, value) -> resDic.put(value, key));
newList.add(resDic);
}
System.out.println("Original Array of Dictionary" + list);
System.out.println("Reversed Array of Dictionary" + newList);
}
Java :
Simple approach, No need for java 8
Map<String,String> map=new HashMap<>();
Map<String,String> mapInv=new HashMap<>();
for (String key : map.keySet())
mapInv.put(map.get(key), key);
Java 8:
forEach() is a new method to iterate the elements. It is defined in Iterable and Stream interface.
Map<String,String> map=new HashMap<>();
Map<String,String> mapInv=new HashMap<>();
map.forEach((key, value) -> mapInv.put(value, key));
Kotlin :
val map: Map<String, String> = HashMap()
val mapInv: MutableMap<String?, String> = HashMap()
for (key in map.keys) mapInv[map[key]] = key

Categories