Removing Values From a Map in a loop - java

I am trying to compare two maps and remove values from one map that are contained in a second map. Here is the code:
HashMap<String, String> firstMap = new HashMap<>();
HashMap<String, String> secondMap = new HashMap<>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
if(!firstMap.equals(secondMap)){
firstMapIterator.next();
for(String key : firstMap.keySet()){
if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
firstMapIterator.remove();
break;
}
}
}
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");
Now, the code does remove an element from the map but not the one I was expecting. As you can see in the code in firstMap I have entered a third key of which is the one I expect to be removed. However, this is the final contents of firstMapI seem to be getting.
{keyOne=valueOne, THIS KEY WILL BE REMOVED=valueThree}
Any ideas? Thanks
Edit: The goal of this code is to:
- Compare two maps
- Increment through each key
- Remove key from firstMap if it is not found in secondMap

You can do this in just one line:
HashMap<String, String> firstMap = new HashMap<>();
HashMap<String, String> secondMap = new HashMap<>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
// Remove everything from firstMap that is in secondMap.
firstMap.keySet().removeAll(secondMap.keySet());
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");
See the JavaDoc for Map.keySet():
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. ... The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations....

You don't need to iterate over the maps.
You can simply do
firstMap.keySet().removeAll(secondMap.keySet());
This will remove all keys from the first map that are present in the second map.
Also, you can remove all keys in the first map that are not in the second map using:
firstMap.keySet().retainAll(secondMap.keySet());

You are not using the iterator correctly. You only advance the iterator once (firstMapIterator.next()), so the first key obtained by the iterator will be the one removed from the Map, regardless of the current key in the for(String key : firstMap.keySet()) loop.
You don't need the for loop:
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
while (firstMapIterator.hasNext()) {
if(!secondMap.containsKey(firstMapIterator.next())) {
firstMapIterator.remove();
break;
}
}

As others have already said, you can do it in one single line:
firstMap.keySet().removeAll(secondMap.keySet());
Another way would be by using the Collection.removeIf method:
firstMap.keySet().removeIf(k -> secondMap.containsKey(k));
The above can be rewritten as follows:
firstMap.keySet().removeIf(secondMap::containsKey);

check your firstMapIterator.next(); add into for loop
HashMap<String, String> firstMap = new HashMap<String, String>();
HashMap<String, String> secondMap = new HashMap<String, String>();
firstMap.put("keyOne", "valueOne");
firstMap.put("keyTwo", "valueTwo");
firstMap.put("THIS KEY WILL BE REMOVED", "valueThree");
System.out.println("\nMAP ONE\n" + firstMap + "\n");
secondMap.put("keyOne", "valueOne");
secondMap.put("keyTwo", "valueTwo");
System.out.println("\nMAP TWO\n" + secondMap + "\n");
Iterator<String> firstMapIterator = firstMap.keySet().iterator();
if(!firstMap.equals(secondMap)){
for(String key : firstMap.keySet()){
firstMapIterator.next();//add here in for loop
if(firstMap.containsKey(key) && !secondMap.containsKey(key)){
firstMapIterator.remove();
break;
}
}
}
System.out.println("\nMAP ONE MATCHING MAP TWO?\n" + firstMap + "\n");

Related

3D HashMap java get entries

I'm currently try to build my own elasticsearch (with less more capabilities and experience) to filter my firebase database, I don't use elasticsearch nor Algolia because I want to make all by myself.
Right now I've come up with this method:
1) get all keywords from my child nodes in firebase
2) add them in a 3D HashMap
For now it arranges my data like I want:
Map<String, Map<String, Map<String, String>>> map = new HashMap<>();
Ex.: "Restaurants" { "Some restaurant Name" { "keywords": "Some,keywords,here" }
All I want to do now is to print all values as a way to get further in my code.
Here's how I'm trying to print:
for (Map.Entry<String, Map<String, Map<String, String>>> entry : map.entrySet()) {
Log.w("MAP =====> ", entry.getKey() + ": " + entry.getValue());
for (Map.Entry<String, Map<String, String>> entry1 : map.get(entry.getKey()).entrySet()) {
Log.w("MAP2 =====> ", entry1.getKey() + ": " + entry1.getValue());
for (Map.Entry<String, String> entry2 : map.get(entry.getKey()).get(entry1.getKey()).entrySet()) {
Log.w("MAP3 =====> ", entry2.getKey() + ": " + entry2.getValue());
}
}
}
I can't seem to be able to go further than the first for loop...
Here's my log:
W/MAP =====>: Restaurants: {}
W/MAP =====>: Hikes: {}
W/MAP =====>: Sports: {}
As you can see, Logs for "MAP2" and "MAP3" are not showing, How can I iterate trough all?
Thanks in advance,
Good day/evening/night!
PS.: I know that firebase querying exists, I don't want to use .startAt() or .endAt() ,etc.

Swap values of two map

I'm a beginner,
I want to create a new map hm3 by using two old maps hm1 and hm2 and in that map I need value of second map as key and value of first map as value
For example : if map hm1 is containing a1 as key1 and abc as value1 and it also containing a2 as key2 and xyz as value2 and there is another map hm2 which contains a1 as key1 and b1 as value1 and also containing a2 as key2 and b2 as value2 then in the map hm3 I need b1 as key1 and abc as value1 and b2 ans key2 and xyz as value2
public class MapInterchange {
public static void main(String[] args) {
HashMap<String, String> hm1 = new HashMap<String, String>();
Map.Entry m1;
hm1.put("a1", "abc");
hm1.put("a2", "xyz");
for (Map.Entry m : hm1.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
HashMap<String, String> hm2 = new HashMap<String, String>();
hm2.put("a1", "b1");
hm2.put("a2", "b2");
for (Map.Entry m : hm2.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
HashMap<Object, Object> hm3 = new HashMap<Object, Object>();
Iterator itr = ((Set<Entry<String, String>>) hm1).iterator();
while (itr.hasNext()) {
hm3.put(((Entry) hm2).getValue(), ((Entry) hm1).getValue());
}
for (Map.Entry m : hm3.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
The exception I'm getting is : Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Set
at com.sid.MapInterchange.main(MapInterchange.java:34)
Please provide the corrected code, I will be very thankful
You can't cast a HashMap to a Set of entries. Use the entrySet method.
Iterator<Map.Entry<String,String>> itr = hm1.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String,String> entry = itr.next();
hm3.put(entry.getKey(), entry.getValue());
}
EDIT: I'm not sure this code does what you want to do, but it overcomes your error. It's not clear what you are trying to swap.
If the mapping of the values is based on the keys, your code should be :
Iterator<Map.Entry<String,String>> itr = hm1.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String,String> entry = itr.next();
hm3.put(hm2.get(entry.getKey()), entry.getValue());
}
This assumes that all the keys of hm1 appear in hm2 (otherwise you'll have a null key in your output Map).

.asFormUrlEncoded() to retrieve data from hashMap<String, String>

I'm sending a video file along with some user details to my play framework application using MultipartRequest, the user details are added to a hashmap Map<String, String> myMap;on the server side I have retrieved my video file using .asMultipartFormData();
I was trying to retrieve my map using .asFormUrlEncoded(); but that uses Map<String, String[]>
So I've only been able to retrieve one value from my hash map, if I try to retrieve anymore using this code
for(int i =0; i < myMap.size(); i++){
String param = "param" + (i + 1);
System.out.println(myMap.get(param)[i]);
}
I get an arrayOutOfBounds error, is there an alternative solution to retrieve the data from the MultipartFormData, or can I implement my loop differently?
maybe I shouldn't be using .asFormUrlEncoded();at all to retrieve the hashmap?
EDIT
I've modifed my code to use an iterator
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value);
}
This prints my key, but returns Ljava.lang.String;# for the values, I think this is because the .asFormUrlEncoded(); is expecting a <String, string[]>, but my hashMap uses <String, String> any solution to this?
This was the solution:
Iterator<String> myVeryOwnIterator = myMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String[] value= myMap.get(key);
System.out.println(key + " " + value[0]);
}

Create a list of array

i want to create a list that each row contain an array like this :
key1 ->value1
key2 ->value2
key3 ->value3
(key and value are string)
How can i do this ?
If your key must be a String, then you want to use a Map rather than an array. And you want/need a List<Map<String, String>>.
Here's an example:
//declaring and initializing the list of maps
//line below works for Java 7
//List<Map<String, String>> listOfMaps = new ArrayList<>();
//if you want/need to use Java 6 then use the following
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
//declaring, initializing and filling a map
//line below works for Java 7
//Map<String, String> map1 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "Luiggi");
map1.put("lastname", "Mendoza");
map1.put("maintag", "Java");
//declaring, initializing and filling another map
//line below works for Java 7
//Map<String, String> map2 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "Foo");
map2.put("lastname", "Bar");
map2.put("maintag", "Scala"); //I have nothing against scala
//add maps into the list
listOfMaps.add(map1);
listOfMaps.add(map2);
//Show contents of the list and map
System.out.println(listOfMaps);
//Traverse each element of the List to access key and value
int index = 0;
//it is better to use Iterator or enhanced for each than using List#get(index)
for (Map<String, String> map : listOfMaps) {
System.out.println("Printing element " + index++);
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("--------------------------");
}
You can use an
ArrayList<Map<String, String>>()
This would have the following structure
List index 0: Key1 -> value 1, Key2 -> value 2
List index 1: Key3 -> value 3
So to put a key value pair:
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);
map.put(key1, value1);
list.add(map);
So to get a value from a key in the first index of the list:
String value = list.get(0).get(key)
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "1");
map.put("key2", "2");
Map<String, String> anotherMap = new HashMap<String, String>();
anotherMap .put("key3", "3");
anotherMap .put("key4", "4");
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
listOfMaps.add(map);
listOfMaps.add(anotherMap);
Why do you need this list? What do you need to do with it? Or is this just an exercise?

how to iterate a list like List<Map<String,Object>>

I have a method which is returning List<Map<String,Object>>.
How to iterate over a list like List<Map<String,Object>>?
It sounds like you're looking for something like this:
List<Map<String, Object>> list; // this is what you have already
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
}
List<Map<String, Object>> list = getMyMap();
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
Loop through list of maps
Handle map entries
with java 1.8 (8) you can re-write it like:
list.forEach(item ->
item.forEach((k, v) -> System.out.println(k + ": " + (String)v)
);
I'm posting you one simple Example of List<Map<String,Object>>.
public static void main(String[] args){
Map<String,Object> map1 = new HashMap<>();
map1.put("Map1 Key1", (Object) "Map1 value1");
map1.put("Map1 Key2", (Object) "Map1 value2");
Map<String,Object> map2 = new HashMap<>();
map2.put("Map2 Key1", (Object) "Map2 value1");
map2.put("Map2 Key2", (Object) "Map2 value2");
List<Map<String,Object>> list = new ArrayList<>();
list.add(map1);
list.add(map2);
list.stream().forEach(mapsData->{
mapsData.entrySet().forEach(mapData->{
System.out.println("Key:"+mapData.getKey()+ " Value:"+mapData.getValue());
});
});
}
This should work:
List<Map<String, Object>> list = ...
for (Map<String, Object> map : list)
{
...
}
You can also use an iterator or the get method within a for loop to access the elements within the List.
Map<String, String> map = new HashMap<>();
map.put("First", "1");
map.put("Second", "2");
map.put("third", "3");
map.put("four", "4");
// here is the logic
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
This is an easy way to iterate over a list of Maps as my starting point. My List had one Map object inside with 3 values
List<Map<String, Object>>
using Java's functional programming in a rather short and succinct manner. The purpose here was to pull out all the maps stored in a list and print them out. I could have also collected the values etc.
answerListOfMaps.stream().map(map -> map.entrySet())
.forEach(System.out::println );
output in Eclipse IDE console looked like this:
[isAllowed=true, isValid=true, cardNumber=672xxxxxxxxxxx]
x's for Obfuscation
alternate way:
answerListOfMaps.stream().flatMap(map -> map.entrySet().stream())
.forEach( entry -> System.out.println(entry.getKey() + ":" + entry.getValue()) );
console:
isAllowed:true
isValid:true
cardNumber:672xxxxxxxxxxx

Categories

Resources