This question already has answers here:
Does Java have a HashMap with reverse lookup?
(7 answers)
Closed 9 years ago.
I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?
My Map is
Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");
Now i want to create an another map and put it in other way as i told above. ie,
Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");
Anybody has idea? Thanks
Like so:
Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
col2.put(e.getValue(), e.getKey());
}
Assuming your values are unique in your hashmap, you can do like this.
// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
String currentValue = valueIterator.next();
// Find the value in old HashMap
Iterator<String> keyIterator = col.keySet().iterator();
while(keyIterator.hasNext()){
String currentKey = keyIterator.next();
if (col.get(currentKey).equals(currentValue)){
// When found, put the value and key combination in new HashMap
col1.put(currentValue, currentKey);
break;
}
}
}
Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.
Related
I have method that should return Map<Strings, List<String>> but in the mean time my method gives me a Map<Strings, Object>, I want to transfer the values of object into a List of Strings.
Here is the current code:
#SuppressWarnings("unchecked")
static Map<String, List<String>> getQueryParameters(JsonObject inputJsonObject) {
JsonArray parameters = inputJsonObject.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).findFirst();
Map<String, Object> paramMap = queryParameters.get().getMap();
paramMap contains key and value , values could be an arrays of integers
so I want to put them into the map below:
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
My solution is this which did not work correctly
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
Map<String, Object> paramMap = queryParameters.get().getMap();
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
if (!mystore.containsKey(key)) ;
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
}
I was a key holding another key as value and is just a mix up , any suggestions?
After debuging what happens i see that mystore holds both "key and value" together as a key and value it hold the next "key and value as value
Should be something like this:
while (it.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
String key = next.getKey();
Object value = next.getValue();
if (!mystore.containsKey(key)) mystore.put(key, new LinkedList<String>());
mystore.get(key).add(value.toString());
}
I'm not writing a program for you, but instead help you in finding a problem. You are confused with Entry. If you are using IDE, you should solve it easier. Look for this line :
String key = it.next().toString();
Entry has a K,V pair. The iterator returns an EntrySet and thus usage to get key is it.next().getKey() and it.next().getValue()
Now that you have a correct key, please go on debugging. Instead of putting and getting and manipulating in below lines of your code. Put with correct value instead?
Yours:
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
What about?:
Entry entry = it.next();
//Get key and value here. DO coding using Entry's methods
List<String> ll = new LinkedList<String>();
ll.add(value)
mystore.put(key, ll);
Tip: Always have the Javadoc or reference documentation handy for knowing more. That's how you learn the language. Refer:https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm newbie with Java
Is it possible to convert a String, or a String[] as the keys of an Hashmap?
I mean:
String keysToConvert = "key1,key2,key3";
into
HashMap<String, Double> hashmap = new HashMap<String, Double>();
[apply in some way the keys of the string]
hashmap.get("key2");
I know that hashmap.get("key2");has no value in this moment. I just would know if there is a way to load the keys in an HashMap.
hashmap.put("key2", 1.0d);
System.out.println(hashmap.get("key2")); // prints 1.0
This is the basic usage of a Map
If you have String[], you can add them using a for-each loop:
String[] keys = {"key1", "key2", "key3"};
HashMap<String, Double> hashmap = new HashMap<String, Double>();
for (String key : keys) {
hashmap.put(key, null);
}
I have this ArrayList
public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
and I want to convert this to:
HashMap<String, String> comparemap2 = new HashMap<>();
What I want is: I want all the Items inside the ArrayList and want to put them into the HashMap
My HashMap looks like:
KEY VALUE
job_id 032014091029309130921.xml
job_id 201302149014021492929.xml
job_id 203921904901920952099.xml
EDIT:
Later I want to compare this map with an existing map:
Properties properties = new Properties();
try {
properties.load(openFileInput("comparexml.kx_todo"));
} catch (IOException e) {
e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
compareMap.put(key, properties.get(key).toString());
}
HashMap<String, String> oldCompareMap = new HashMap<>();
for (HashMap key : xmlFileNames) {
oldCompareMap.putAll(key);
}
isEqualMaps(oldCompareMap, compareMap);
I only want to compare, if the filename exists in the compareMap. If not, than add it to the xmlFileName Map
I've looked up in StackOverFlow, how I can convert ArrayList to HashMap. But the other Threads treat data types like Item or Product.
I hope you can help me!
Kind Regards
Given...
public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
then something like this should do it.
HashMap<String, String> nhm = new HashMap<>();
for (HashMap xmlFileHm : xmlFileNames ) {
nhm.putAll(xmlFileHm);
}
but be aware if you have duplicate keys in your hashmaps they will get overwritten.
You should also think about coding to interfaces. Take a look at Map and List rather than typing your collections to implementations (ArrayList and HashMap). Take a look at this thread which is quite interesting What does it mean to "program to an interface"?
Depending on what you are trying to do as well you might consider a MultiMap as this might server your purposes better
Edit After update to the question...
A multimap would be better here with one key and multiple values. Although arguably if the key never changes then you could just store the values in a list. For multiamps you can use Google's guava library or do one yourself. For example (not checked for compilation errors as Im doing this from my head)
Map<String, List<String>> m = new HashMap<>();
if (m.containsKey("key")) {
m.get("key").add("new value");
}
else {
List<String> l = new ArrayList<>();
l.add("new value");
m.put("key", l);
}
You can create a new HashMap, then iterate through the list and put all elements from the map from the list to the main map.
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
for (Map<String, String> mapFromList : list) {
map.putAll(mapFromList);
}
You can try something like this..
ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
HashMap<String, String> comparemap2 = new HashMap<>();
for(HashMap<String, String> i:xmlFileNames){
comparemap2.putAll(i);
}
You may need to consider the case of duplicate keys. else they will get override.
Create a new map and put All each element of arrayList to the map.
But in that case if you have same keys in two element of arrayList (hashmap) then it will override the previous one.
This question already has answers here:
Intersection of java.util.Map
(6 answers)
Closed 8 years ago.
I have two HashMaps, say HashMapA and HashMapB. What would be an efficient way of finding keys that exists in both HashMaps? My current implementation looks like this:
Integer key;
/* create iterator */
Iterator<Map.Entry<Integer, Foo>> it = HashMapA.entrySet().iterator;
/* iterate through HashMapA using iterator*/
while (it.hasNext()) {
key = it.next().getKey();
if (HashMapB.containsKey(key)) {
/* matching key found */
System.out.println("Got one: " + key);
}
}
This appears to work, but looks quiet inefficient. Is there something like
Integer keyInBothMaps = HashMapA.containsKeyOf(HashMapB);
?
You are looking at the keys of the map so start with the keySet();
You can then look at the Set interface and see the method retainAll
http://docs.oracle.com/javase/8/docs/api/java/util/Set.html#retainAll-java.util.Collection-
This gives you:
map1.keySet().retainAll(map2.keySet())
However that will modify the map so you should copy the set:
new HashSet<>(map1.keySet()).retainAll(map2.keySet())
You can use Set.retainAll.
Here's an ugly example:
Map<String, String> m0 = new HashMap<String, String>();
m0.put("a", "a");
m0.put("b", "b");
Map<String, String> m1 = new HashMap<String, String>();
m1.put("c", "c");
m1.put("b", "b");
Set<String> s = new HashSet<String>(m0.keySet());
s.retainAll(m1.keySet());
System.out.println(s);
Output
[b]
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