I have two tables in my database i.e. Menu and Sub_Menu... I have retrieved the data from those two tables using JOIN queries and it looks like this
`SELECT menu.menu_name AS menu_name, sub_menu.sub_menu_name FROM menu LEFT JOIN user_category ON menu.user_category_id = user_category.user_category_id LEFT JOIN sub_menu ON menu.menu_id = sub_menu.menu_id WHERE user_category.user_category_name = "Normal";`
After this what i have done is I have used LinkedHashMap<String, String> to store the results. Now, the problem rises here. When I print the output, the last value of the duplicate key is only displayed and others are omitted... What i want to display is a unique key with multiple values.. I have tried it using LinkedHashMap<String, ArrayList<String>> but can't get it right !!!
`
LinkedHashMap<String, ArrayList<String>> menuSubMenu = new LinkedHashMap<String, ArrayList<String>>();`
`ArrayList<String> subMenu = null;`
`String key = null;`
while (rs.next()) {
key = rs.getString("menu_name");
if (key.equals(rs.getString("menu_name"))) {
key = rs.getString("menu_name");
subMenu = new ArrayList<String>();
subMenu.add(rs.getString("sub_menu_name"));
} else {
subMenu = null;
}
menuSubMenu.put(key, subMenu);
}
Sorry but you code sample is a bit confusing but you can try this way:
LinkedHashMap<String, ArrayList<String>> menuSubMenu = new LinkedHashMap<String, ArrayList<String>>();
while(true){
String key = rs.getString("menu_name");
if(!menuSubMenu.containsKey(key)){
menuSubMenu.put(key, new ArrayList<String>());
}
menuSubMenu.get(key).add(rs.getString("sub_menu_name"));
}
Hope it helps
I'm going to guess that the problem is where you are putting the data into your map instead of where you take it out. You need to make certain that you are putting the array list back into the map after you create a new one and that you're pulling that array list back out the next time you encounter that word.
I have to agree The Thom You have to check for already existing entries in your Hashmap:
LinkedHashMap<String, ArrayList<String>> menuSubMenu = new LinkedHashMap<String, ArrayList<String>>();
while (rs.next()) {
final String key = rs.getString("menu_name");
final ArrayList<String> subMenu = menuSubMenu.get(key);
if (subMenu == null) {
subMenu = new ArrayList<String>();
menuSubMenu.put(key, subMenu);
}
subMenu.add(rs.getString("sub_menu_name"));
}
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())
}
I'm trying to write a little vocabulary test. The LinkedHashMap vocabulary consists of vocabulary. They key is a french word and the value is an english word. I already have a GUI but I'm struggling to get a random french word from the vocabulary and its position to find out if the entered word is right. I tried to do it with an ArrayList but then I only get the value but I also need the key to show which word the person has to translate. Any help is appreciated.
LinkedHashMap<String, String> vocabulary = new LinkedHashMap<String, String>();
Random random = new Random();
int number = random.nextInt(ReadExcelFile.lastRowNumber);
String value = (new ArrayList<String>(vocabulary.values())).get(number);
Put the keys into a list, then pick a random one:
// Do once after loading (or changing)
List<String> keyList = new ArrayList<>(vocabulary.keySet());
Random random = new Random();
int number = random.nextInt(vocabulary.size());
String key = keyList.get(number);
String value = vocabulary.get(key);
You can go in the following way!
Map<String, String> myMap = new LinkedHashMap<String, String>();
myMap.put("Bonjour", "Hello");
myMap.put("moi", "me");
myMap.put("tue", "you");
List<String> val = new ArrayList<String>(myMap.values());
int randomIndex = new Random().nextInt(val.size());
String randomValue = val.get(randomIndex);
System.out.println(randomValue);
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 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);
For an Android application that I'm building for my internship, I'm trying to display a list
of tickets from the current logged in user and display them in a ListView. Let me paste some of my code to let you see where I'm at currently:
JSONArray finalResult = finalResultObject.getJSONArray(TAG_TICKETS);
System.out.println("this is finalResult: " + finalResult);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
for (int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
if (c.has(TAG_CLIENT_NAME) && !c.isNull(TAG_CLIENT_NAME)) {
String clientName = c.getString(TAG_CLIENT_NAME);
map.put("client_name_map", clientName);
// System.out.println(clientName);
}
if (c.has(TAG_PROJECT_NAME) && !c.isNull(TAG_PROJECT_NAME)) {
String projectName = c.getString(TAG_PROJECT_NAME);
map.put("project_name_map", projectName);
}
// adding HashList to ArrayList
ticketList.add(map);
// System.out.println(map);
}
ListAdapter adapter = new SimpleAdapter(SecondActivity.this, ticketList, R.layout.list_item, new String[] { "client_name_map", "project_name_map" }, new int[] { R.id.client_name,
R.id.project_name });
eventualListAdapter = adapter;
I've got a couple of prints in between, left them in there to let you guys see what I'm looking at right now. My problem is that I do get the required number of items, but it repeats the same item (so it does loop through the array, but doesn't update the values). I'm currently completely new to Android, and therefore still figuring out which kind of Adapters to use etc.
In the end I'm passing the adapter to eventualListAdapter, which I created within the main thread, so I can easily call it to update the UI (I'm not sure if this is anywhere near a clean way, just trying to get things working at this point)
Thanks in advance,
Dennis
You are using the same HashMap instance for all Itens. Just move the HashMap creation to inside the loop:
// adding each child node to HashMap key => value
for (int i = 0; i < finalResult.length(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = finalResult.getJSONObject(i);
if(c.has(TAG_CLIENT_NAME)&&!c.isNull(TAG_CLIENT_NAME)){
String clientName = c.getString(TAG_CLIENT_NAME);
map.put("client_name_map", clientName);
//System.out.println(clientName);
}
if(c.has(TAG_PROJECT_NAME)&&!c.isNull(TAG_PROJECT_NAME)){
String projectName = c.getString(TAG_PROJECT_NAME);
map.put("project_name_map", projectName);
}
// adding HashList to ArrayList
ticketList.add(map);
//System.out.println(map);
}