I want to prepare a HashMap in such way that
Key : Country Code
Value : List of returned orderEntries
the following process data method process every 5 orderEntry which can be from any country.
let me make it more clear. I have list of orderEntries that come from different countries now I want to put these entries into map based on country key. Like if 20 entries coming from US then US will be the key and 20 Entries would be the values. But problem is that I don't want to create a list for each county inside map.
public void processSegmentData(final List resultSet)
{
for (final Object orderEntry : resultSet)
{
if (orderEntry instanceof OrderEntryModel)
{
String countryCode = null;
final OrderModel order = ((OrderEntryModel) orderEntry).getOrder();
if (order.getDeliveryAddress() != null)
{
countryCode = order.getDeliveryAddress().getCountry().getIsocode();
}
orderEntriesMap.put(Config.getParameter(countryCode+".return.pid"), orderEntries);
}
}
}
so you are after a hashmap which contains a linked list Something along the lines of:
public HashMap<String, LinkedList<OrderEntryModel>> processSegmentData(final List resultSet) {
HashMap<String, LinkedList<OrderEntryModel>> orderEntriesMap = new HashMap<String, LinkedList<OrderEntryModel>>();
for (final Object orderEntry : resultSet) {
if (orderEntry instanceof OrderEntryModel) {
String countryCode = null;
final OrderModel order = ((OrderEntryModel) orderEntry).getOrder();
if (order.getDeliveryAddress() != null) {
countryCode = order.getDeliveryAddress().getCountry().getIsocode();
}
if (!orderEntriesMap.containsKey(countryCode)) {
orderEntriesMap.put(countryCode, new LinkedList<OrderEntryModel>());
}
orderEntriesMap.get(countryCode).add((OrderEntryModel) orderEntry);
}
}
return orderEntriesMap;
}
would be an example based on the source code you provided guessing object names.
But problem is that I don't want to create a list for each county
inside map.
I understand your problem but map store unique key, you can not store same country code.
you have to use Map<String, List<String>>() that will hold your country code as key and then put your values inside List<String>.
after doing this if you have any problem edit your question will help you to resolve that.
Just Create a Map<String,List<String>>. and follow the following approach
Map<String,List<String>> countryMap = new HashMap<String, List<String>>();
for (final String orderEntry : orders){
if(countryMap.containsKey(orderEntry.getCountry())){
countryMap.get(orderEntry.getCountry()).add(orderEntry);
}else{
//create a new list and add orderEntry
countryMap.put(orderEntry.getCountry(),orderEntry);
}
}
You need to modify this according to your stuff
You could use Guava's Multimap to simplify things. A Multimap allows you to store multiple entries against a single key, e.g.:
Multimap<String, OrderEntry> orderEntriesMultimap = HashMultimap.create();
for (final Object orderEntry : resultSet) {
// omitted...
orderEntriesMultimap.put(Config.getParameter(countryCode+".return.pid"), orderEntry);
}
You can then retrieve all the associated values by key:
Collection<OrderEntryModel> entries = orderEntriesMultimap.get(key);
Related
I have a list of custom object,
public class Assignmentsdata {
String assignmentId;
String teacherId;
String groupName;
String sectionId;
String levelId;
String startTime;
}
ArrayList<Assignmentsdata> list = new ArrayList<>();
lets say there are 20 elements in that list.
Now I want to get the output which is a hashmap of startTime as a key and the Value would be a new HashMap of GroupID and a list of Assignments of those that had the same groupName.
OutPut Example
HashMap<startTime,HasMap<groupName,List> hashMap = new HashMap();
a little more insight about the problem: First I want to categorise based on startTime(Month) then i want to categorise based on groupName, Thanks in advance.
I have successfully categorised based on group name and created a map through below code:
for( int i = 0; i<assignmentsdataArrayList.size();i++ ){
if (hashMap.size()>0){
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}else {
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}
After that I am lost on how to categorise this hashmap based on the startDate and create a hashmap that would look like the above hashmap in the output heading.
your code may throw a NullPointerException at the first if branch
if (hashMap.size()>0)
{hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
the map.size()>0 doesnt means the Value of GroupName has put a new ArrayList already.
the anwser of using loop should like this
Map<String, Map<String, List<Assignmentsdata>>> map = new HashMap<>();
for (Assignmentsdata assignmentsdata : list) {
if (!map.containsKey(assignmentsdata.getStartTime())) {
map.put(assignmentsdata.getStartTime(), new HashMap<>());
}
Map<String, List<Assignmentsdata>> startTimeMap = map.get(assignmentsdata.startTime);
if (!startTimeMap.containsKey(assignmentsdata.getGroupName())) {
startTimeMap.put(assignmentsdata.getGroupName(), new ArrayList<>());
}
startTimeMap.get(assignmentsdata.groupName).add(assignmentsdata);
}
or you could use the java stream().collect(Collectors.groupingBy()) api to get the result easily
Map<String, Map<String, List<Assignmentsdata>>> result = list.stream()
.collect(Collectors.groupingBy(Assignmentsdata::getStartTime,Collectors.groupingBy(Assignmentsdata::getGroupName)));
I am answering my own question as I solved it if anyone has a better answer please passed your answer aswell, ill accept another answer suitable and efficient answer.
for( int i = 0; i<assignmentsdataArrayList.size();i++ ){
if (hashMap.size()>0){
if (hashMap.get(assignmentsdataArrayList.get(i).getGroupName())==null){
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}else{
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}else {
hashMap.put(assignmentsdataArrayList.get(i).getGroupName(),new ArrayList<Assignmentsdata>());
hashMap.get(assignmentsdataArrayList.get(i).getGroupName()).add(assignmentsdataArrayList.get(i));
}
}
// above part is already in the question. the second part i looped through the hashMap then the list once again, and checking if list and map entry have same group name, then made the startdate key that indexed element from the list.
HashMap<String, Map.Entry<String, ArrayList<Assignmentsdata>>> hashMapHashMap = new HashMap<>();
for (var entry : hashMap.entrySet()){
for( int j = 0; j<assignmentsdataArrayList.size();j++ ){
if (assignmentsdataArrayList.get(j).getGroupName()==entry.getKey()){
hashMapHashMap.put(assignmentsdataArrayList.get(j).getStartTime(),entry);
}
}
hashMapHashMap.put(entry.getValue().get())
}
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 a class with two methods: the startAPI() calls the API classes to extract entities and returns the entities and the occurrence of the entities. I need this return value in two different methods from another class, but as soon as I call the second method (countApiOcc()) the map I pass is empty. How can I use the returned map in two different methods?
public class Topic {
public void calculateNoFeedback(String language, List<String> api, List<String> corr) {
Map<String, Object> apis = startAPI(api, textList);
CountTopics countT = new CountTopics();
ArrayList<String> topics = countT.getTopics(apis);
countT.countApiOcc(topics, apis);
}
public Map<String, Object> startAPI(List<String> selectedAPI, List<String> text) {
Map<String, Object> apisValues = new HashMap<String, Object>();
//do stuff to extract the entities and return entities
return apisValues;
}
}
The CountTopic() class looks as follows, and, explained in short, user can select which or how many APIs he wants to use to extract entities and in the class CountTopic() the method getTopics() should find the topics every selected API found and countApiOcc() I need the frequency of the selected entities (all of this works) it is just the map I need in the second method.
public ArrayList<String> getTopics(Map<String, Object> apiV) {
System.out.println("apiV: "+apiV);
Iterator iterator = apiV.entrySet().iterator();
mapSize = apiV.size();
System.out.println("Size of the map: "+ mapSize);
while (iterator.hasNext()) {
Map.Entry entries = (Map.Entry)iterator.next();
String key = entries.getKey().toString();
switch(key) {
case "valuesMS":
Map<String, Object> mapMicrosoft = (Map<String, Object>) apiV.get(key);
ArrayList<String> microsoft = (ArrayList<String>) mapMicrosoft.get("topicArrayMS");
microsoftTopicLowerCase.addAll(microsoft);
topicsMultiset.addAll(microsoft);
break;
case "valuesGate":
Map<String, Object> mapGate = (Map<String, Object>) apiV.get(key);
ArrayList<String> gate = (ArrayList<String>) mapGate.get("topicArrayGA");
//store the values for finding the topics which are found from every selected API
//store the values from the api to lower case to find the index later (needed for how often this api found the topic
gateTopicLowerCase.addAll(gate);
topicsMultiset.addAll(gate);
break;
}
iterator.remove();
}
//rest code: compare the Arrays to find the same topics
iterator.remove();
There's your culprit. You're emptying your map. Don't do this, and it will work. From my limited view on your code, there doesn't seem to be any reason to modify your map. But in case it would be necessary, you should make a copy of the map at the beginning of your method, and work on this copy. Generally it's a bad idea to modify your input parameters, unless that is the specific purpose of that method.
I am struggling with following:
I need to create a method which returns a collection of all values that specify some particular selection criterion specified by one or more arguments.
My MAP consists of PPS numbers(keys) and values( town, name, surname, place of work ) Both are strings .
However, I am not sure what I need to do to get the values after placin in the map.
/**
*This method returns a collection of all people who work for CO-OP
*/
public Set<String> selectKeys(String factory)
{
for (Set<String>eachTaxPayers : taxPayersList.values())
{
if(taxPayersList.values().contains(factory))
{
Set<String>eachClients = taxPayersList.keySet();
System.out.println(taxPayersList.keySet());
}
}
return null ;
}
Could someone help me please?
This is a code how Map is populated.
public class Tax
{
Map<String, Set<String>>taxPayersList;
public Tax()
{
taxPayersList = new HashMap<>();
Set<String>taxPayersDetails = new HashSet<>();
taxPayersDetails.add(" Eddie Donegan");
taxPayersDetails.add("Prodieco");
taxPayersDetails.add("Limerick");
taxPayersList.put("4481908A", taxPayersDetails);
taxPayersDetails = new HashSet<>();
taxPayersDetails.add(" Paddy Power");
taxPayersDetails.add("Covenant");
taxPayersDetails.add("Limerick");
taxPayersList.put("6088989B", taxPayersDetails);
taxPayersDetails = new HashSet<>();
taxPayersDetails.add(" Mikey Obama");
taxPayersDetails.add("Prodieco");
taxPayersDetails.add("Limerick");
taxPayersList.put("6788910B", taxPayersDetails);
}
}
I want only to return the key's( PPS numbers) for people who works for the same company
public Set<String> selectKeys(String factory) {
// our return Set
Set<String> factoryWorkers = new HashSet<>();
// Let's iterate over the map entries
for (Map.Entry entry : taxPayersList.entrySet()) {
// Let's grab the value of the current map entruy
Set<String> eachTaxPayers = entry.getValue()
// Risky move
if(eachTaxPayers.contains(factory)) {
// add the key (PPS) to the return set
factoryWorkers.add(entry.getKey());
}
}
return factoryWorkers;
}
FYI, the line marked as "Risky Move" is not the best approach.
Though unlikely, it's possible a city has the same name as factory.
You'd be better using an Iterator on the Set and comparing against the 2nd value.
Even better, instead of having a Map>
you could have a Map
where Employee has fields such as name, city and factoryName.