I have created the data structure as shown below that is google based guava table and it is shown below
final Table<String, String, List<String>> values = HashBasedTable.create();
values.put("bon", "currency", Lists.newArrayList("ccdd","rode1","cwey","Certy"));
below is the way in which i am iterating over this collection
Map <String , List<String>>fmap = new HashMap < String , List<String>>();
for (Cell<String, String, List<String>> cell1: values.cellSet()){
if (cell1.getRowKey() != null && cell1.getRowKey().equalsIgnoreCase("bon") )
{
fmap.put(cell1.getColumnKey(), cell1.getValue());
}
}
now i want to modify my condition in such a way that if row key contains the value of bon
and the column key contains these values "ccdd","rode1","cwey","Certy" then it should fill the map
named fmap such that on iteration map would look like this
Key Value
ccdd currency
rode1 currency
cwey currency
Certy currency
please advise how to achieve this
as the solution advise is still not working please
Instead of iterating through all the values in the Guava Table. Try to get the row with row key bon and then loop through the valid column keys to populate your map.
Map <String , List<String>>fmap = new HashMap < String , List<String>>();
List<String> validColumnKeys = Arrays.asList("ccdd","rode1","cwey","Certy");
Map<String, List<String>> row = values.row("bon");
for(String columnKey:validColumnKeys) {
fmap.put(columnKey, row.get(columnKey));
}
Related
I created a Map<Integer, ArrayList<String>> map and I would like to compare each value in map with one ArrayList<String> likeList and get key if they match. I will bring the key to use later.
I tried to run my code like this, but it doesn't work because it returns nothing:
for (int key : map.keySet()) {
if(map.get(key).equals(likeList)){
index = key;
Log.d("IndexN", String.valueOf(index));
}
}
Then, I tried this:
int index = 0;
for (Map.Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
if(entry.getValue().equals(likeList)){
index = entry.getkey();
}
}
Do you have any idea?
Add a list of the key to store all match
List<Integer> indices = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
indices.add(key);
}
}
It does not return index when I try the code above.
From this comment, I understood that as soon as you find a match in the map, the index should be recorded and further processing should be stopped. In other words, either there is only one match of likeList in the map or you want to find the first match of likeList in the map. If yes, you need to break the loop as soon as the match is found (shown below).
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
Log.d("IndexN", String.valueOf(index));
break;
}
}
Note that this will give you the same value, each time you execute it, only when the map has only one match of likeList or the map is a LinkedHashMap. If it is a HashMap and it has more than one matches of likeList, you may get a different value each time you execute it because a HashMap does not guarantee the order of its entries.
However, if there can be multiple matches of likeList in the map and you want to log all the matches as well as get the list of the corresponding keys, you can do it as follows:
List<Integer> indexList = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key).equals(likeList)) {
Log.d("IndexN", String.valueOf(index));
indexList.add(key);
}
}
// Display the list of corresponding keys
System.out.println(indexList);
Issue : There will 3 records in testcaseInputs . All the three records are iterated, but at end the "rows" map has only one record which is iterated in the last. I want rows map should contain all the three records.
Issue 2: The iteration takes record1, then record 2, record 3 .. again it takes record 1 or 3 for iteration. I don't know why.
public void addinputtosc() {
try {
Map<String, List<JsonNode>> testrecords = null;
Map<String, String> rows = new Hashmap<String, String>();
// this function takes the input sheet , sheet name and returns data in Map<String, List<JsonNode>> format.
testrecords = fetchScenariosData("C:\\testData.xlsx", "input", "inputParam");
Iterator<Map.Enry<String, List<JsonNode>>> entries = testRecords.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, List<JsonNode>> entry = entries.next();
String scenarioName = entry.getKey();
List<JsonNode> testcaseInputs = entry.getValue();
if (scenarioName.equalsIgnoreCase("TestCase1")) {
ListIterator<JsonNode> listIterator = testCaseInputs.listIterator();
while (listIterator.hasNext()) {
for (JsonNode tcinputs :testCaseInputs) {
String keyValue = tcinputs.toString();
String newKeyValue = keyValue.replaceAll("[{}]", "");
String[] keyValue1 = newKeyValue.split(",");
for (String j : keyValue1) {
String[] keyValueorg = j.split(":");
row.put(keyValueorg[0].substring(1, keyValueorg[0].length() - 1), keyValueorg[1].substring(1, keyValueorg[1].length() - 1));
}
}
}
}
}
} catch (exception e) {
e.printStackTrace();
}
}
Issue : There will 3 records in testcaseInputs . All the three records
are iterated, but at end the "rows" map has only one record which is
iterated in the last. I want rows map should contain all the three
records.
This is happening because of this line :
rows.put(keyValueorg[0].substring(1, keyValueorg[0].length() - 1), keyValueorg[1].substring(1, keyValueorg[1].length() - 1));
when you are procesing frist JsonNode suppose this as per your example
{"File Source Env.":"Unix","TC_ID":"tc1","File Path":"/tmp/test.dat","Date":"20190101"}
the HashMap rows will contain content as :
{Date=20190101, path=/tmp/test.dat, TC_ID=tc1, File Source Env.=Unix}
now when again this codeis executed for second JsonNode suppose this :
{"File Source Env.":"Unix-qa","TC_ID":"tc2","File Path":"/tmp/test1.dat","Date":"20190201"}
as per your code , keys which will be calculated for this new record (keyValueorg[0].substring(1, keyValueorg[0].length() - 1)) is same as the previous key values that are stored in hashmap i.e. Date, File Source Env, TC_ID, Path by the first record.
Since these key values are already present in hashmap there values get updated by new values which is property of PUT operation of HashMap(if key is there then it just override with new values else insert new key in map).
This process will continue and hence only last record values are seen in hashmap.
In order to keep all key-value pairs of all records in single hashmap you need to create different key for each record. Otherwise create a nested hashmap.
Hey guys currently have problem with regards to removing duplicates from hashmap.
Some background:
My hashmap is in this format Map<CompositeKeyBean,ValueBean>.
CompositeKeyBean is in the form (String ID, String hashvalue);
ValueBean is an object.
So if i have a hashmap with values as such:
(ID:1,HashValue:123),Obj1
(ID:1,HashValue:234),Obj1
(ID:1,HashValue:345),Obj1
I need to remove the duplicate keys and only have items with unique IDs. currently I have come up with this, But it does not seem to work, im pretty sure i am doing something wrong.
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
for(int i = 1; i < list.size();i++)
{
if(list.keySet().contains(idvalue))
{
list.remove(i);
}
}
}
My solution for this one would be to declare first an another Map which will be used to hold the number of times that a certain key has appeared in the original Map. For the second time, you can iterate the same map entrySet and remove the duplicates using the declared additional Map as reference.
Map<String, Integer> numberOfInstanceMap = new HashMap<String, Integer>(); //temporary placeholder
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
if(!numberOfInstanceMap.containsKey(idvalue)) {
numberOfInstanceMap.put(idvalue, 1); //initialize the key to 1
} else {
numberOfInstanceMap.replace(idValue, numberOfInstanceMap.get(idValue) + 1); //add 1 to the existing value of the key
}
}
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
Integer i = numberOfInstanceMap.get(idValue);
if(i>1) { //remove duplicate if the key exists more than once
list.remove(idValue);
}
}
If you are expecting duplicate keys, then you can do the following way to handle it while populating the map itself:
Map<String, String> map = new HashMap<>();
if(map.containsKey("ID")){
String oldValue = map.get("ID");
//put logic to merge the value
}else{
map.put("ID","newValue");
}
I would like to create multiple hashmaps from a resultset.
The final result should be something like below;
{
slot_name = recommend,
data = 7,
},
{
slot_name = service,
data = Good,
},
{
slot_name = staff,
data = Great,
},
I tried as below:
HashMap<String, String> data = new HashMap<String, String>();
while (resultSet.next()) {
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
}
But when I printout the value of the hashmap, I get one record as below
System.out.println(data);
{
slot_name = staff,
data = Great,
}
How can I achieve this? Someone assist, thank you
I would recommend to have a list and create a model class(instead of HashMaps) for "slot_name" and "data". Inside loop, construct object and add to the list. The reason, you are not getting as expected, is because, HashMap will have unique keys. So, for the same key when the value is again added, it will get updated.
class YourModel {
String slotName;
String data;
}
// inside loop
list.add(new YourModel(resultSet.getString("name"), resultSet.getString("param_value"));
A HashMap is a key value store. If you put the same key more than once, previous will be overwritten. This is the reason you saw only the last entry in the output.
if you want multiple maps, well create multiple ones.
Eg.,
List<HashMap<String,String> maps = new ArrayList();
while (resultSet.next()) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
maps.add(data);
}
I have following map Map<IndexDerivedKey, Collection<Data<D>>> indexedData in an indexable data structure.
IndexDerivedKey conforms to an Index, an index consists of keys and corresponding values. The keys are used to extract the values from the elements in the indexable data structure.
For example there's an index, which consists of the keys firstName and lastName, we use this index to extract values from objects, which possess these attributes, this operation yields an IndexDerivedKey per object.
That IndexDerivedKey contains the mapping from above keys to their respective values and is used to store the objects in the map indexedData, which I mentioned before. The map value is a collection type, since it is possible for several objects to be equal (with respect to the index).
QUESTION
How can I extract all objects with firstName = "John", hereby ignoring the value of lastName. Obviously I can iterate over all keys and check the value of firstName in O(n).
But since the IndexDerivedKey {firstName = "John"} is a subset of all other keys with firstName = "John", e.g. {firstName = "John", lastName = "Smith"}, I suppose there has to be a more efficient way. Maybe utilizing a TreeSet?
1
public IndexDerivedKeyImpl(Index index, Map<String, String> keyValues)
{
this.keyValues = keyValues;
this.index = index;
for (String key : keyValues.keySet())
if (!index.supportsKey(key))
throw new IndexKeyMismatchException(key, index);
}
2
// in data.Index.index(Indexable)
#Override
public IndexDerivedKey index(Indexable data)
{
Map<String, String> keyValues = new HashMap<String, String>();
IndexDerivedKey key = new IndexDerivedKeyImpl(this, keyValues);
for (String k : keys)
{
String value = data.get(k);
if (value != null)
keyValues.put(k, value);
}
return key;
}
If the search is always on a specific order, make a key class with a Comparable, and equals.
And then use a SortedMap, like TreeMap. This is navigable too. You might for instance use subMap(fromKey, toKey)
If you want to access your Map with an other key, you are better off using an other Map:
Map<String, Collection<Data<D>>> dataByFirstName = // ...
Where the keys are the first names.