Map to hold multiple sets of key and values - hashmap

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

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.

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);

How to add individual elements of an object in an Arraylist through a for loop?

I am trying to add all elements of an object into ArrayList. elements of the object are of different type.
e.g. object Employee having attributes like emp_id,name,address,DOB.
I want to store each attribute as an object in an ArrayList. Like,
ArrayList[1] = Employee.emp_id
ArrayList[2] = Employee.name
ArrayList[3] = Employee.address
I want to do it dynamically. Like, in future more attributes are added in this object, without doing a manual work. Is there a way to create an array List?
ArrayList must be of the same type. You can have an ArrayList of type in which you can do what you are doing, since all objects in Java extend Object. If you are trying to store different Object types in an arraylist, however, this is not possible.
You may know that first part, just was a little unclear in your post.
Here's how to do it with objects using reflection:
//make sure you import java.lang.reflect.*
public void addMyFields(Employee e){
ArrayList<Object> list = new ArrayList();
for (Field field : emp.getClass().getDeclaredFields())
{
field.setAccessible(true);
list.add(field.get(emp);
}
}

How to search and sort in J2me (ascending or descending)

I am wondering about how to search in J2ME. I have been searching in the internet, so many result show to me, and I see in Java2s.com I got a result use RecordFilter and matches method for search in record store.
But my problem is, when I need to pass 2 or more parameters into it. How can result matches with these parameter?
And how to sort descending or ascending like bubble sort?
Concatenate your searches into a single String variable. Separate each of them with ; for example. In the code of the matches method explode the String to get each search criteria.
To make the filter in effect create an instance of SearchFilter and call the matches method with the concantenated String as its param.
For the sort implement the RecordComparator interface ; implement the compare method to build your sort criteria. Make a google search about j2me+recordcomparator to see examples about how to make sorts.
EDIT :
In the code of the matches method explode the String param obtained from the byte[] param. Treat each String exploded to make the criteria.
As I understand you want to pass two string as a search criteria when you wrote :
SearchFilter search = new SearchFilter(txtSearch.getString(), strType);
So in the constructor there should be two params !!!
When you want to make the matching then call
if searchFilter.matches((search1+";"+sType).getBytes())
Then explode the candidate param into two String when you code the matches method.
When I save my Data in RMS I save it as a String[] like I want to save Name, Age,Salary,EmpID for each employee I save it create an array and convert it to bytes and save it in RMS. When i retrieve it i do the reverse process. Now if i want to get employee with names starting with A and with salary 10000 i use the following filter
class UtilFilter implements RecordFilter{
public UtilFilter(String str_searchText,String str_searchText1)
{
this.str_searchText = str_searchText.toLowerCase();
this.str_searchText1 = str_searchText1.toLowerCase();
}
public boolean matches(byte[] bt_byteData)
{
String str_str = "";
String str_str1 = "";
//here goes code how u get back ur String[] from RMS say u get it in Data
str_str = Data[0].trim();
str_str1 = gd_cd.Data[2].trim();
if(str_searchText != null && str_searchText1 != null && str_str.equals(str_searchText) && str_str1.equals(str_searchText1 ))
{
return true;
}
else
{
return false;
}
}
}
This way i can filter any no of parameters.Hope tht helps! :)

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