how to remove duplicates from the map using java - java

I am adding few item on finalMapNode using map for creating json for d3. and i dont want any duplicates item. how to check.finalmapNode put the duplicates item on map.I dont want duplicated item.if item is avalible then it should not put on map . if id is avalable then item should not put in the finalmapnode.
Note::if id is avalable then item should not put in the finalmapnode.
List<Map<String, Object>> listNodeMap = new ArrayList<Map<String, Object>>();
Map<String, Object> finalMapNode2 = new TreeMap<String, Object>();
Map<String, Object> finalMapNode = new TreeMap<String, Object>();
//if id is avalable then item should not put in the finalmapnode.
finalMapNode.put("id", Integer.parseInt(source2.get(z))+"");
finalMapNode.put("name",source.get(z));
finalMapNode.put("displayname", source.get(z));
finalMapNode.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode.put("type", "location");
finalMapNode.put("group", 0);
finalMapNode.put("opacity", 100);
finalMapNode2.put("id", Integer.parseInt(target2.get(z))+"");
finalMapNode2.put("name",target.get(z));
finalMapNode2.put("displayname", target.get(z));
finalMapNode2.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode2.put("type", "location");
finalMapNode2.put("group", 0);
finalMapNode2.put("opacity", 100);
listNodeMap.add(finalMapNode);
listNodeMap.add(finalMapNode2);

When you try to add the KEY which is already available in the hashmap, then it will override the previous KEY's VALUE and adds the new VALUE. So its up to you to validate the map before trying to add the KEY and VALUE. You can use finalmapnode.containsKey(KEY); to validate and then add the VALUES.
EDIT
Just check the below method works for you!
private static void putMap(String strKey, Object object, Map<String, Object> map){
if(!map.containsKey(strKey)){
map.put(strKey, object);
}
}
In your case, instead of using
finalMapNode.put("name",source.get(z));
you can use
putMap("name",source.get(z), finalMapNode);
The above method will not override the values if you add duplicate KEYS. Pass the KEY, VALUE and the Map which you declared as finalMapNode.
Try this and see.
Thanks!

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");
HashMap<String, String> mapNew = new HashMap<String, String>();
for(String s :map.keySet())
{
//String value = map.get(s);
System.out.println(s +"=="+map.get(s));
if(!mapNew.containsValue(map.get(s)))
{
mapNew.put(s, map.get(s));
}
}
System.out.println(mapNew);
before :{A=1,B=2,c=2,D=3,E=3}
Output after removing duplicates : {A=1,B=2,D=3}

Related

Create or Update key value pairs in both maps

I've map of key value pairs with each value being a map of key value pairs.
Something like
Map<String, Map<String, Integer> outMap = new HashMap<>();
Map<String, Integer> inMap = new HashMap<>();
inMap.put("i11", 111);
inMap.put("i21", 121);
outMap.put("o1", inMap);
How would I handle the entry where I can create/update at both levels of the map using java 8 ?
Input would be outer key/inner key and value. So we should we able to add a new entry is it doesn't exist in outer map. If the entry exists in outer map then insert the new entry in inner map if it doesn't exist else update the inner map with new value.
What you want to achieve can be done with this single line of code:
outerMap.computeIfAbsent(outerKey, k -> new HashMap<>()).put(innerKey, value)
But without these methods, you can achieve the same with just get() and put():
Map<String, Integer> innerMap = outerMap.get(outerKey);
if (innerMap == null) {
innerMap = new HashMap<>();
outerMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, value);
HOW TO UPDATE THE SINGLE-VALUE AND MULTIPLE VALUES AT THE SAME TIME SIMULTANEOUSLY IN TWO MAPS
NTOE:
givenMap.computIfAbsent(k,Funtion) -> if key in given map is null or absent, then compute the value using funtion and add into the given map
Map<String, Map<String, Integer>> outMap = new HashMap<>();
Map<String, Integer> inMap = new HashMap<>();
inMap.put("i11", 111);
inMap.put("i21", 121);
outMap.put("o1", inMap);
System.out.println(outMap.toString());
System.out.println(inMap.toString());
OUTPUT BEFORE UPDATING:
{o1={i11=111, i21=121}}
{i11=111, i21=121}
//If you want to add one value in the inner hashmap you created:
outMap.computeIfAbsent("newHashMapKey",k -> new HashMap<>()).put("Arpan",2345);
// if you want to add more than 1 value at a time in the inner hashmap
outMap.computeIfAbsent("newHashMapKey2",k -> new HashMap<>()).putAll(new HashMap<String, Integer>(){{
put("One", 1);
put("Two", 2);
put("Three", 3);
}});
System.out.println(outMap.toString());
System.out.println(inMap.toString());
OUTPUT AFTER UPDATING BOTH MAPS AT THE SAME TIME
{o1={i11=111, i21=121}, newHashMapKey2={Two=2, Three=3, One=1}, newHashMapKey={Arpan=2345}}
{i11=111, i21=121}

Updating a certain value of an hashmap containing an hashmap in Java

I have an outerMap which contains an innerMap for each key it got. At first, every innerMap is the same (here, they contain {1=1}.
I want to change the value of one certain innermap, for a certain key.
Here is my code:
public class HelloWorld
{
public static void main(String args[]){
HashMap<String, HashMap<String, Integer>> outerMap = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
outerMap.put("1001",innerMap);
outerMap.put("1002",innerMap);
outerMap.put("1003",innerMap);
innerMap.put("1", 1);
//My attempt to change only one innermap;
Map<String, Integer> map_to_change = outerMap.get("1001");
map_to_change.put("1", 0);
//And then I print them to see if it's working;
for(Map.Entry map : outerMap.entrySet() )
{
System.out.println(map.getKey()+" "+map.getValue());
}
}
}
However, the output here is
1003 {1=0}
1002 {1=0}
1001 {1=0}
Which shows that my code changes all innermaps, and not only the one linked with the key "1001".
What can I do?
You are pointing the same innerMap object in the outerMap,
outerMap.put("1001",new HashMap<String, Integer>());//create separate maps
outerMap.put("1002",new HashMap<String, Integer>());
outerMap.put("1003",new HashMap<String, Integer>());
HashMap<String, Integer> innerMap =outerMap.get("1001");//get the map you want to put value
innerMap.put("1", 1);//assign the value
Update:
If you want to retain a copy of Map which you have already created, you can copy and create a new Map from it using putAll method,
outerMap.put("1001",copyMap(innerMap));
outerMap.put("1002",copyMap(innerMap));
outerMap.put("1003",copyMap(innerMap));
copyMap method looks like,
private static HashMap<String, Integer> copyMap(HashMap<String, Integer> innerMap){
HashMap<String, Integer> copiedInnerMap = new HashMap<String, Integer>();
copiedInnerMap.putAll(innerMap);
return copiedInnerMap;
}

Keep the value of the main map after clearing map

I have mainHolder map which contains another map holder as value I am facing problem when clearing the holder map that I am loosing the vlue of the apple key in the mainHolder map.
How can I Keep the value of the mainHolder map after Clearing the holder map?
Code
import java.util.HashMap;
import java.util.LinkedHashMap;
public class Generator {
public static void main(String[] args) {
LinkedHashMap<String, Object> holder = new LinkedHashMap<String, Object>();
final HashMap<String, LinkedHashMap<String, Object>> mainHolder = new LinkedHashMap<String, LinkedHashMap<String, Object>>();
holder.put("firstName", "Alex");
holder.put("lastName", "Cruz");
mainHolder.put("apple", holder);
holder.clear(); //After Clearing the map I am loosing the value in the mainHolder for 'apple'
holder.put("quantity", 13);
mainHolder.put("apple", holder);
System.out.println("Test");
}
}
mainHolder
should contain at the end the following:
[apple:[firstName: Fadi, lastName: Cruz, quantity:13]]
The reason this is happening is because you are using the same key.
If the map previously contains a mapping for the key, the old value
is replaced.
Update
<>.add(map) will put a reference to map in the list, so it's not a
copy. When you then do map.clear() afterwards, it erases the content
of the map in the list too, because it is the very same object. Do
<>.add(map.clone()) instead or (preferably) do map = new HashMap<>();
solution
LinkedHashMap<String, Object> holder = new LinkedHashMap<String, Object>();
final HashMap<String, LinkedHashMap<String, Object>> mainHolder = new LinkedHashMap<String, LinkedHashMap<String, Object>>();
holder.put("firstName", "Alex");
holder.put("lastName", "Cruz");
mainHolder.put("apple", holder);
holder = new LinkedHashMap<>();
LinkedHashMap<String, Object> temp = mainHolder.get("apple");
temp.put("quantity",13);
mainHolder.put("apple",temp);
System.out.println(mainHolder);

android arraylist get hashmap position

I have an ArrayList HashMap like the one below.
ArrayList<HashMap<String, String>> mArrType = new ArrayList<>();
with the following values added into it
HashMap<String, String> map;
map = new HashMap<String, String>();
map.put("type", "TRIMMER");
map.put("request", "5");
map.put("actual", "0");
mArrType.add(map);
map = new HashMap<String, String>();
map.put("type", "HAND ROUTER");
map.put("request", "6");
map.put("actual", "0");
mArrType.add(map);
map = new HashMap<String, String>();
map.put("type", "AIR COMPRESSOR");
map.put("request", "6");
map.put("actual", "0");
mArrType.add(map);
Question is how can i get the position of a hashmap from arraylist. eg : hashmap with 'type' trimmer has a position 0 in arraylist, I want to retrieve the position value "0"
I'll write a small util method
private static int getTrimmerTypeMapPosition(ArrayList<HashMap<String, String>> mArrType) {
for (int i = 0; i < mArrType.size(); i++) {
HashMap<String, String> mp = mArrType.get(i);
if (mp.get("type").equals("TRIMMER")) {
return i;
}
}
return -1;
}
To make this method very generic, have "type" and "TRIMMER" as method params, so that you can just pass any key and value pairs to check with.
That's not efficiently possible with your data structure. You can either store the own position in each HashMap or loop through all entries and search for the one with the type you are looking for.
You can, of course, define another HashMap<String, Integer> which maps all your type strings to the corresponding ArrayList index.
Others answer is also correct, but you can do this thing using Java8 also.
E.g.:
int index = IntStream.range(0, mArrType.size()).
filter(i -> mArrType.get(i).get("type").equals("TRIMMER"))
.findFirst().getAsInt();

How to replace ALL keys in java map? [duplicate]

This question already has answers here:
Changing HashMap keys during iteration
(5 answers)
Closed 6 years ago.
I want to replace keys in my map.
I have the following code:
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
map.put("e", "5");
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
Object o = next.getValue();
//how to add new element ?
//...
iterator.remove();
}
I want to achieve map with keys
a1->1
b2->2
c3->3
d4->4
e5->5
If I use in loop map.put(next.getKey() + next.getValue(), next.getValue()); it will lead to ConcurrentModificationException.
To avoid a ConcurrentModificationException, you need to add the new key/value pairs to a separate map, and then use putAll to add that map into the original one.
Map<String, Object> newMap = new HashMap<>();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
iterator.remove();
newMap.put(...); // Whatever logic to compose new key/value pair.
}
map.putAll(newMap);

Categories

Resources