Need help in constructing HashMap of String Key with Map of Strings - hashmap

I have the list of projects(String) and respective users which I am taking from users as an input :
Project1,User1
Project1,User2
Project1,User3
Project2,User4
Project2,User5
I would like to have this data in the format like:
Project1: User1,User2,User3
Project2:User4,User5
I am trying the same thing to put in hashmap
HashMap<String, HashSet> hsp = new HashMap<String, HashSet>();
HashSet<String> userHash = new HashSet<String>();
Can any one help me to understand how to do it? I am accepting both project name and user name from user.

Initialize HashMap and HashSet as follows
HashSet<String> hashset=new HashSet<String>();
HashSet<String> hashset2=new HashSet<String>();
HashMap<String, HashSet> hashmap=new HashMap<String, HashSet>();
Now add elements to hashset
hashset.add("User1");
hashset.add("User2");
hashset.add("User3");
hashset2.add("User4");
hashset2.add("User5");
Finally add HashSet to HashMap
hashmap.put("project1", hashset);
hashmap.put("project2", hashset2);
So your desired o/p will be as follows
Hash map is {project2=[User4, User5], project1=[User3, User2, User1]}

Related

How to merge Collectors.counting() to existing HashMap

my current goal is to merge counted value(Collectors.counting()) to existing HashMap,
see the structure as below:
this data was from tons of columns with same data,
so this way was kind of best solution to count many of same values.
But if possible, I want to put those values (Long) in HashMap before inserting into database.
Is here any great solution, please help.
(Or if this structure is very bad; Thanks for your advice in advance :)).
Thanks!
original data was List<Map<String, Object>>,
and result data came out with Map<Object, Long>.
Map<Object, Long> result = errData.stream()
.collect(Collectors.groupingBy(d -> d, Collectors.counting()));
Desired output should be:
result:
"data" -> 0.0
"execPlanId" -> "QPLN-20220412-001"
"columnId" -> "DSCHDRUG"
"tableName" -> "ODS_APIPDLST"
"execId" -> 156
"errCount" -> 341 (currently on "value" from result HashMap)
First, change the type of the result as Map<Map<String, Object>, Long>.
Then, you can iterate/stream this map and add a new field as desired.
List<Map<String, Object>> resWithErrCount = result.entrySet().stream()
.map(entry -> {
Map<String, Object> map = new HashMap<>(entry.getKey());
map.put("errCount", entry.getValue());
return map;
})
.collect(Collectors.toList());
Note: This creates a new HashMap with the added errCount field and all maps are collected into a list.

HashMap return the lasted record if it has multiple records with the same key, but different value

I have the following map..
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1,"tom");
hmap.put(1,"jerry");
hmap.put(1,"Jeff");
System.out.println(hmap.get(1));
The output is "Jeff"
Why it always returns the latest record?
An HashMap, store items in "key/value" pairs. The key is unique inside a Map. So when you are doing a put on an existing key, you are overwriting the value, you lost the previous one. Thus, always the latest inserted record is returned.
You can check this link https://www.w3schools.com/java/java_hashmap.asp or the official doc at https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

Map to hold multiple sets of key and values

I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json

How to define composite key for a column family and then reference it using Hector?

where can I find samples for this?
Most of my code using ColumnFamilyTemplate to do CRUD on the data records, see below. Once I have the composite key defined, can I still use ColumnFamilyTemplate to access my data having composite keys?
private static final ColumnFamilyTemplate<UUID, String> template =
new ThriftColumnFamilyTemplate<UUID, String>(
Bootstrap.keyspace,
"User",
UUIDSerializer.get(),
StringSerializer.get(),
HFactory.createMutator(Bootstrap.keyspace, UUIDSerializer.get()));
It shouldn't matter which API you use to do the CRUD on the records; CompositeType (or DynamicCompositeType) is just another type (e.g. similar to UUID) which has a corresponding serializer (CompositeSerializer). So, your example might become:
private static final ColumnFamilyTemplate<Composite, String> template =
new ThriftColumnFamilyTemplate<Composite, String>(
Bootstrap.keyspace,
"User",
CompositeSerializer.get(),
StringSerializer.get(),
HFactory.createMutator(Bootstrap.keyspace, CompositeSerializer.get()));
Only extra would be to create the Composite before using template (assume composite of UUID & Long):
Composite key = new Composite();
key.addComponent(someUUID, UUIDSerializer.get());
key.addComponent(someLong, LongSerializer,get());
ColumnFamilyResult<Composite,String> result = template.queryColumns(key);
When fetching results, one way to get the components of the key:
myUUID = result.getKey().get(0, UUIDSerializer.get());
myLong = result.getKey().get(1, LongSerializer,get());
If you define a composite key, you also need to tell Cassandra (>0.8.1) to use CompositeType as the comparator. Here is a complete example starting from defining CompositeType schema to programming a range query:
http://randomizedsort.blogspot.com/2011/11/cassandra-range-query-using.html

Can Automapper map from a Dictionary of properties to a flat destination?

Source contains a property bag in a Dictionary. Can Automapper map the entries in the Dictionary to individual properties of the Destination based upon matching the dictionary keys with the names of the properties on the destination type?
Example:
public class Destination
{
public int ProdNumber;
public string Title;
}
public class Source
{
public Dictionary<string, object> values = new Dictionary<string, object>();
}
where the values Dictionary will have two entries, one with a key of "ProdNumber" and one with a key value of "Title". There will likely be entries in the dictionary that have keys that don't match any property in the Destination and they should be ignored. There will be multiple properties of each primitive data type (int, string, etc) - so I presume I can't use a simple set of TypeConverters.
Any suggestions?
Thanks,
Chris
Unfortunately it is not possible at the moment, but it is planned for the next version. Read this thread as it discusses the plans and a work around.

Resources