Iterate over HashMap<String, List<Class>> - java

how would i iterate over the list "values" that one string "key" has.
Map<String, List<wordsStreamed>> hm = new HashMap<String, List<wordsStreamed>>();
hm.put(wordChoosen, sw.streamMethod());
hm has one key and over 10,000 values. i want to iterate over the values so i can compare my key with all the values. also i would like to know if this code is the best way to get my String values from the list of classes.
hm.values().iterator().next().get(i).toString()

To iterate over your HashMap's values, you can use fast-enumeration.
What you probably need here is to iterate over the key set, then access the List for each value and iterate over each of the List's items to compare it to the key.
For instance:
Map<String, List<Object>> hm = new HashMap<String, List<Object>>();
for (String key : hm.keySet()) {
// gets the value
List<Object> value = hm.get(key);
// checks for null value
if (value != null) {
// iterates over String elements of value
for (Object element : value) {
// checks for null
if (element != null) {
// prints whether the key is equal to the String
// representation of that List's element
System.out.println(key.equals(element.toString()));
}
}
}
}
Note I've replaced your WordsStreamed class here with the Object class.

i want to iterate over the values so i can compare my key with all the value
looks like misuse of data structure , generally you should not have to iterate in such scenario and values should be mapped with key
you should enter the values those are logically mapped with keys so while retrieving you won't have to iterate through all they keys and associated values

A more efficient way
for(List<String> valueList : map.values()) {
for(String value : valueList) {
...
}
}
for details click

Related

Removing duplicate linked value from ArrayList java

we are facing a challenge in implementing one of our client requirement, using java as code technology.
we need to format the input given by the system, to display the data in a userfriendly format.
below is the data as input to our program.
its a java map with key as string and value as a list of strings
OP1004=[],
OP1006=[OP1004]
OP1005=[OP1003]
OP1009=[OP1006, OP1044, OP1046, OP1004],
OP1016=[OP1008, OP1009, OP1044, OP1005, OP1004],
output we are expecting as below.
OP1004=[],
OP1006=[OP1004]
OP1005=[OP1003]
OP1009=[OP1006, OP1044, OP1046], //here 1004 is deleted
OP1016=[OP1008, OP1009, OP1005, OP1004], //here 1044 is deleted
here, if we observe closely, we want to delete the repeated values from the list, that is
if we go thru the bottom, that is OP1016 contains the list as OP1008, OP1009 etc.. where OP1009 also has the list as OP1006, OP1044 etc.. where OP1006 again has the list as OP1004
so here we want to delete OP1004 from OP1009 because its already mapped to other(OP1006) OPID which is part of OP1009.
actually we are displaying this in a hierachy/flowchart diagram, so we want to delete duplicate navigation to the items.
Please help us in providing solution. appreciate your help in advance.
Thanks
Your problem boils down to checking whether elements of a list are present in other lists but these list are present in a map so you need to maintain the key-value pair.
This is how you can achieve that.
Loop over map and get the key and list of values, add a condition to check whether list is empty and contains more than 1 values.
Loop over same map again, get the key and add a condition to check whether the first loop key is equal to second loop key this is to avoid checking for same list. Add one more condition to check whether list is empty and contains more than 1 values.
Now you can remove elements from a list if those elements are present in another list by using List.removeAll() method.
Sample code
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Example {
public static void main(String[] args) {
List<String> firstList = new ArrayList<String>();
firstList.add("");
List<String> secondList = new ArrayList<String>();
secondList.add("OP1004");
List<String> thirdList = new ArrayList<String>();
thirdList.add("OP1003");
List<String> fourthList = new ArrayList<String>();
fourthList.add("OP1006");
fourthList.add("OP1044");
fourthList.add("OP1046");
List<String> fifthList = new ArrayList<String>();
fifthList.add("OP1008");
fifthList.add("OP1009");
fifthList.add("OP1044");
fifthList.add("OP1005");
fifthList.add("OP1004");
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("OP1004", firstList);
map.put("OP1006", secondList);
map.put("OP1005", thirdList);
map.put("OP1009", fourthList);
map.put("OP1016", fifthList);
for (Map.Entry<String, List<String>> keyAndValue: map.entrySet()) {
String key = keyAndValue.getKey();
List<String> values = keyAndValue.getValue();
if (values.isEmpty() || (values.size() < 2)){
continue;
}
for (Map.Entry<String, List<String>> mapKeyAndValue: map.entrySet()) {
String key1 = mapKeyAndValue.getKey();
if (key.equals(key1)){
continue;
}
List<String> values2 = mapKeyAndValue.getValue();
if (values2.isEmpty() || (values2.size() < 2)){
continue;
}
values2.removeAll(values);
}
}
for (Map.Entry<String, List<String>> keyAndValue: map.entrySet()) {
System.out.println("Key is " + keyAndValue.getKey() + " Values are " + keyAndValue.getValue());
}
}
}
Check Output Here
Key is OP1004 Values are []
Key is OP1006 Values are [OP1004]
Key is OP1005 Values are [OP1003]
Key is OP1009 Values are [OP1006, OP1044, OP1046]
Key is OP1016 Values are [OP1008, OP1009, OP1005, OP1004]
Note - I assumed that you are using HashMap as you didn't specify what kind of map you are using and if you want the map to be ordered then use LinkedHashMap
as HashMap does not store elements in order.
A simple solution would be to change the
Map<String, List<String>> to Map <String<Set<String>>
Let me explain it in a better way:
List list = map.get(str);
Set<String> set = new HashSet<>();
set.addAll(list);
list.clear();
list.addAll(set);
now you can use it in the way you want..
Let me know if you didnt understand any part of it
Pseudo-code: if key exists then remove it from any values (of other keys)
for (String key : map.keySet()){ // iterate through all keys
for (Map.Entry<String, List> mapEntry : map.entrySet()){ // again iterate but this time get Map.Entry
if (!mapEntry.getKey().equals(key)){ // if entry is for other key
((List)mapEntry.getValue()).remove(key); // then remove key from list
// if this map cannot be modified you can keep key, mapEntry in another map here...
}
}
}
Create a set to hold all the values previously displayed. If an item can not be added to this set, then do not add it at all.
Map<String, String[]> original = ...
Set<String> used = new HashSet<>();
Map<String, String[]> reduced = original
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> Arrays.stream(entry.getValue())
.filter(used::add)
.toArray(String[]::new)));

Java - Adding another String value to existing HashMap Key without overwriting?

I was wondering if someone would be able to help with regards to adding another String value to an existing key within a HashMap in Java?
I understand that you can add a Key-Value pair using the this.put("String", "String") method. However, it overwrites the existing value, whereas I would like multiple values stored and paired, with the same key?
Thanks for your help.
What are you hoping to achieve here?
A Map (the HashMap) in your case is a direct "mapping" from one "key" to another value.
E.g.
"foo" -> 123
"bar" -> 321
"far" -> 12345
"boo" -> 54321
This means that if you were to try:
myHashMap.get("foo");
It would return the value 123 (of course, the type of the value you return can be anything you want).
Of course, this also means that any changes you make to the value of the key, it overrides the original value you assigned it, just like changing the value of a variable will override the original one assigned.
Say:
myHashMap.put("foo", 42);
The old value of "foo" in the map would be replaced with 42. So it would become:
"foo" -> 42
"bar" -> 321
"far" -> 12345
"boo" -> 54321
However, if you need multiple String objects that are mapped from a single key, you could use a different object which can store multiple objects, such as an Array or a List (or even another HashMap if you wanted.
For example, if you were to be using ArrayLists, when you are assigning a value to the HashMap, (say it is called myHashMap), you would first check if the key has been used before, if it hasn't, then you create a new ArrayList with the value you want to add, if it has, then you just add the value to the list.
(Assume key and value have the values you want)
ArrayList<String> list;
if(myHashMap.containsKey(key)){
// if the key has already been used,
// we'll just grab the array list and add the value to it
list = myHashMap.get(key);
list.add(value);
} else {
// if the key hasn't been used yet,
// we'll create a new ArrayList<String> object, add the value
// and put it in the array list with the new key
list = new ArrayList<String>();
list.add(value);
myHashMap.put(key, list);
}
You can do like this!
Map<String,List<String>> map = new HashMap<>();
.
.
if(map.containsKey(key)){
map.get(key).add(value);
} else {
List<String> list = new ArrayList<>();
list.add(value);
map.put(key, list);
}
Or you can do the same thing by one line code in Java 8 style .
map.computeIfAbsent(key, k ->new ArrayList<>()).add(value);
Would you like a concatenation of the two strings?
map.put(key, val);
if (map.containsKey(key)) {
map.put(key, map.get(key) + newVal);
}
Or would you like a list of all the values for that key?
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
String key = "key";
String val = "val";
String newVal = "newVal";
List<String> list = new ArrayList<String>();
list.add(val);
map.put(key, list);
if (map.containsKey(key)) {
map.get(key).add(newVal);
}
As others pointed, Map by specification can have only one value for a given key. You have 2 solutions:
Use HashMap<String, List<String>> to store the data
Use Multimap which is provided by 3rd party Google Collections lib
As described in Map interface documentation Map contains a set of keys, so it is not capable of containing multiple non-unique keys.
I suggest you to use lists as values for this map.
Store value as list under map So if key is test and there are two values say val1 and val2 then key will be test and value will be list containing val1 and val2
But if your intention is to have two separate entries for same key, then this is not Map is designed for. Think if you do map.get("key"), which value you expects
You could use Map<String, Collection<String>> but adding and removing values would be cumbersome . Better way is using guava Multimap - a container that allows storing multiple values for each key.
You can't directly store multiple values under a single key, but the value associated with a key can be any type of object, such as an ArrayList, which will hold multiple values. For example:
import java.util.ArrayList;
import java.util.HashMap;
public class HashMapList {
HashMap<String, ArrayList<String>> strings = new HashMap<String, ArrayList<String>>();
public void add(String key, String value) {
ArrayList<String> values = strings.get(key);
if (values == null) {
values = new ArrayList<String>();
strings.put(key, values);
}
values.add(value);
}
public ArrayList<String> get(String key) {
return strings.get(key);
}
public static void main(String[] argv) {
HashMapList mymap = new HashMapList();
mymap.add("key", "value1");
mymap.add("key", "value2");
ArrayList<String> values = mymap.get("key");
for (String value : values) {
System.out.println(value);
}
}
}
it's impossible,because String is immutable if you use the String as the key of map the same key's value has the same hashcode value.

Compare keys with llist of values Java

Assuming the TreeMap<String,List> one and its copy as bellow,
i want to compare all keys in the first one with all values in the second one. If a key has no match in values, as AUF_1060589919844_59496 and AUF_1421272434570_1781 in this case, i want to get the key and its values back.
{AUF_1060589919844_59496=[AUF_1086686287581_9999,
AUF_1086686329972_10049, AUF_1079023138936_6682],
AUF_1087981634453_7022=[AUF_1421268533080_1741, AUF_1421268568003_1743],
AUF_1421268533080_1741=[AUF_1421268719761_1776],
AUF_1421272434570_1781=[AUF_1087981634453_7022]}
copy of above
{AUF_1060589919844_59496=[AUF_1086686287581_9999,
AUF_1086686329972_10049, AUF_1079023138936_6682],
AUF_1087981634453_7022=[AUF_1421268533080_1741, AUF_1421268568003_1743],
AUF_1421268533080_1741=[AUF_1421268719761_1776],
AUF_1421272434570_1781=[AUF_1087981634453_7022]}
What I understand from your problem is to get key which are not there in values and its value also. I think there is no need to create copy of it. I am posting a code snippet, I think this will certainly help you
Map<String, List<String>> map = new HashMap<String, List<String>>(); //Add elements in map
Collection<List<String>> list = map.values();
List<String> values = new ArrayList<String>();
for (List<String> listValues : list) {
values.addAll(listValues);
}
for (String key : map.keySet()) {
if (!values.contains(key)) {
System.out.println("key ---->" + key);
System.out.println("Values ------->");
for (String value : map.get(key)) {
System.out.println(value);
}
}
}
If my assumption is correct you want all the keys that are not values;
well this is very dirty way of doing it.
Set<String> keys= new HashSet<String>(one.keySet()); //ensure we don't mess up with the actual keys in the Map
for(List list : one.values()){
keys.removeAll(list); //remove all those Keys that are in values
}
// print out keys that are not values
System.out.println(keys);
Using set will make life easy, as it doesn't contain duplicates, and we can remove values very quicky (using removeAll() method)

How to add HashMap values to List and print the same

I am trying to add map values to list for my scenario as below.
I have select statement which returns n-no of columns and row, I am storing them into List of Hash Map of type String and pass it to some other method to produce an EXCEL file out of the result.
i am unable to see any data in the list
Please advice where i am going wrong.
while (result.next()) {
resultValues.put("PARTC_ID",result.getString("PARTC_ID"));
resultValues.put("FILE_NME",result.getString("FILE_NME"));
resultValues.put("LOC_ID",result.getString("LOC_ID"));
resultValues.put("CRTE_DTE",result.getString("CRTE_DTE"));
resultValues.put("CRTE_BY",result.getString("CRTE_BY"));
value.add(resultValues); resultValues.clear(); System.out.println(value);
}
You're clearing your Map after adding it to the List. The Map references are all thus the same (and empty)... I think you want to make this change -
// resultValues.clear(); // No, if you need another Map... do this
resultValues = new HashMap<String, String>();
Then to iterate your value List try
for (HashMap<String, String> map : value) {
for (String key : map.keySet()) {
System.out.printf("key[%s] = %s\n", key, map.get(key));
}
}

How to put multiple values in Map from a list

I have a list gotitems.
ArrayList<String> gotitems = new ArrayList<String>();
i need to put that list in a hashmap called map.
Map<String,String> map = new HashMap<String,String>();
i had tried this :
for(String s:gotitems){
map.put("a",s);
}
gotitems contains :
First
Second
Third
But the output of :
System.out.println(map.values());
gives :
Third
Third
Third
i had even tried this :
for(String s:gotitems){
for(int j=0;j<gotitems.size();j++){
map.put("a"+j,s);
}
}
but this is also not working.
What am i doing wrong here ?
As per Map put(K,V) method docs
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
You are ovverriding the key each time here .
for(String s:gotitems){
map.put("a",s);
}
change the key each time and try like
for(String s:gotitems){
map.put(s,s);
}
This is because you are putting all the items in the map against the same key "a"
map.put("a");
You need to store each element against a unique key so add something like this:
int count = 0;
for(String s:gotitems){
map.put("a" + count,s);
count++;
}
You are trying to put three Strings in the map under the same key "a". Try to use unique keys for your values.
You're putting all your items in the Map with the same key: "a".
You should have a unique String key for each value.
For instance:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
Map<String, String> map = new LinkedHashMap<String, String>();
for (String s: list) {
map.put(s, s);
}
System.out.println(map);
Output:
{one=one, two=two, three=three}
Note the LinkedHashMap here: it maintains the order in which you put your key/value pairs.
Edit Of course if your List does not have unique values, moving its values as keys to a Map will overwrite some of the Map's values. In that case you want to ensure your List has unique keys first, or maybe use a Map<Integer, String> with the index of the List's value as key to the Map, and the actual List value as value to the Map.
When you write
for(String s:gotitems){
map.put("a",s);
}
you will trash any existing entry in the map held against the key "a". So after your iteration, your map will contain just one entry corresponding to the last iterated value in gotitems.
To use a map effectively you need to consider what your keys will be. Then use map.put(myKeyForThisItem, s) instead. If you don't have an effective scheme for the keys then using a map is pointless as one tends to use the keys to extract the corresponding values.
As for your second approach, it would be helpful if you could define "it is not working" a little clearer: perhaps iterate through the map and print the keys and values.
Please note that in a map, a key can point to at most one value. In your case, you are doing the following mappings:
"a" -> "one"
then you overwrite it as
"a" -> "two"
then you overwrite it as
"a" -> "three"
remember: a key can point to at most one value. However, a value can be pointed at by multiple keys.
This is wrong:
for(String s:gotitems){
map.put("a",s);
}
Since you are using "a" common key for all values, last inserted key-value pair would be preserved, all previous ones would be overridden.
This is also not correct:
for(String s:gotitems){
for(int j=0;j<gotitems.size();j++){
map.put("a"+j,s);
}
}
you are putting n*n times into map, though you want only n (gotitems.size()) items into map.
First decide on key which you want to use in map, copying List into Map one approach could be use index as key:
for(int j=0;j<gotitems.size();j++){
map.put("KEY-"+j,gotitems.get(j));
}
Output should be:
KEY-0 First
KEY-1 Second
KEY-2 Third
I have reproduce your codes. The problem is that you are assigning the same key to different value. This should work.
import java.util.*;
public class testCollection{
public static void main(String[] args){
ArrayList<String> gotitems = new ArrayList<String>();
gotitems.add("First");
gotitems.add("Second");
gotitems.add("Third");
Map<String,String> map = new HashMap<String,String>();
String x = "a";
int i = 1;
for(String s:gotitems){
map.put(x+i,s);
i++;
}
System.out.println(map);
}
}

Categories

Resources