How to merge Collectors.counting() to existing HashMap - 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.

Related

JOOQ: fetchGroups() always returns list with only one element

I'm new to JOOQ and currently fail to map a joined query to Map<K, List<V>>: the list always only contains one element.
Here's my code:
DSL.using(...)
.select(ORDER.fields())
.select(ORDER_ITEM_ARTICLE.fields())
.from(ORDER)
.leftOuterJoin(ORDER_ITEM_ARTICLE).on(ORDER.ID.eq(ORDER_ITEM_ARTICLE.ORDER_ID))
// to Map<InOutOrder, List<OrderItemArticle>>
.fetchGroups(
r -> r.into(ORDER).into(InOutOrder.class),
r -> r.into(ORDER_ITEM_ARTICLE).into(OrderItemArticle.class)
)
// map to InOutOrder
.entrySet().stream().map( e -> {
// e.getValue() always returns list with only 1 element?!
e.getKey().articles = e.getValue();
return e.getKey();
})
.collect(Collectors.toList())
;
Say I have 1 row in ORDER and 2 corresponding rows in ORDER_ITEM_ARTICLE. Running the SQL returned by .getSQL() (after .fetchGroups()), returns me 2 rows as expected, so I assumed the fetchGroups() call will populate my list with two entries as well?!
What am I missing?
Thanks!
Update:
As requested, the InOutOrder class:
public class InOutOrder extends Order {
public List<OrderItemArticle> articles;
public List<OrderItemOther> others;
public List<OrderItemCost> costs;
public List<OrderContact> contacts;
public List<EmailJob> emailJobs;
}
So this is just an extension of the JOOQ POJO class and is used for JSON communication with the API clients...
fetchGroups() simply puts objects in a LinkedHashMap. You have to adhere to the usual Map contract, which means implementing equals() and hashCode(). Without it, each object you're creating (or which jOOQ is creating for you) will use identity comparison, so you get every "value" only once in the result.

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

Hazelcast get list of column values

I want to get a list of column values instead of getting the whole IMap in hazelcast. Is it possible to get a list of column values in hazelcast? (Example : List which contains all the names of a Student from Student table)
I think you could build your own EntryProcessor extracting the column (property) you're interested in and send only this back. It would look like:
class MyExtractor extends AbstractEntryProcessor<String, User> {
Object process(Map.Entry<String, User> entry) {
return entry.getValue().getUsername();
}
}
Map<String, Object> result = map.executeOnEntries(new MyExtractor());
I hope this helps and answers your question :)

Hazelcast - query collections of Map values

Assume I have the following as the value in an IMap:
public class Employee{
public int empId;
public List<String> categories;
public List<String> getCategories(){
return this.categories;
}
}
I would like to find all employees that belong to category "Sales". Also, I would like to create an index on getCategories() so that the query returns fast. There seems to be no Predicate available to do this. How do I go about achieving this? It seems like I will have to write a Predicate to do this. Is there example code I can look at that would show me how to build a predicate that uses an index ?
The only way I currently see this happening is to denormalize the data model and use something like a IMap and the following as value:
class EmployeeCategory{int employeeId, String category}
And put an index on category.
It is somewhere on the backlog to provide more advances indices that should be able to do this out of the box.
I tried by iterating the List to a separate Imap and then querying it in the client.
IMap<String,ArrayList< categories >> cache=hazelcastInstance.getMap("cache");
IMap<String, categories> cachemodified = hazelcastInstance.getMap("cachemodified") ;
int[] idx = { 0 };
xref.get("urkey").forEach(cachefelement ->{
cachemodified.put(String.valueOf(idx[0]++),cachefelement);
});
Predicate p = Predicates.equal("categoryId", "SearchValue");
Collection<categories> result = cachemodified.values(p);

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