I use apache-commons-beanutils DynaBean class in order to fetch rows from a database and to handle them outside of the mysql function.
is there a way to convert a DynaBean to a List without iterating through each row and manually creating the list ?
thanks!
so far I didn't get any answers so I wrote the function that iterates through the rows and creates an ArrayList of HashMap type (String, Object).
public ArrayList<HashMap<String,Object>> convertDynaBeanListToArrayList(List<DynaBean> theList) {
ArrayList<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
DynaProperty[] dynaProperties = null;
for (Integer i=0;i<theList.size();i++) {
DynaBean row = theList.get(i);
HashMap<String,Object> resultRow=new HashMap<String,Object>();
// each raw got the same column names, no need to fetch this for every line
if (dynaProperties == null) {
dynaProperties = row.getDynaClass().getDynaProperties();
}
for (Integer j=0;j<dynaProperties.length;j++) {
String columnName=dynaProperties[j].getName();
resultRow.put(columnName, row.get(columnName));
}
result.add(resultRow);
}
return result;
}
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 can't add to my list this query:
// This query always return List<Object[]>
Query buscarRad = AreaPrincipal.em.createNamedQuery("Rad.buscarPorCuil");
buscarRad.setParameter("cuil", cuil);
List<Object[]> listaRad = buscarRad.getResultList();
int i = 0;
for (Object[] filaRad : listaRad) {
// if (filaRad[i].equals(null)) {
if (filaRad[i] != null) {
lvRad.getItems().add(filaRad[i].toString());
}
i++;
}
This is my vector listaRad:
I need all values not null
...but my objects list break at first value and finalize. What's wrong?
You need to use nested loops to iterate over all rows, and then to iterate over all columns within each row. Try this:
for (Object[] filaRad : listaRad) { //for DB rows
for (int i = 0; i < filaRad.length; i++) { //for DB columns within a row
if (filaRad[i] != null) {
lvRad.getItems().add(filaRad[i].toString());
}
}
}
Ideally you should put each column's value in an object's field rather than looping and converting them to toString(). Something like this:
List<MyDbRow> rows = new ArrayList<>();
for (Object[] filaRad : listaRad) {
MyDbRow row = new MyDbRow();
row.setId(fileRad[0]); //may require casting
row.setName(fileRad[1]);
rows.add(row);
}
See if this works for you. First you can put all elements at one level in an Object array list. After that you can loop through that list and check for null elements.
// This query always return List<Object[]>
Query buscarRad = AreaPrincipal.em.createNamedQuery("Rad.buscarPorCuil");
buscarRad.setParameter("cuil", cuil);
List<Object[]> listaRad = buscarRad.getResultList();
List<Object> finalList = new ArrayList<>();
int i = 0;
for (Object[] filaRad : listaRad) {
finalList.add(Arrays.asList(filaRad));
}
for(Object o : finalList){
if (o != null) {
lvRad.getItems().add(o.toString());
}
}
In java 8 you can do like this assuming that lvRad.getItems() is a list
itself
lvRad.getItems().addAll(finalList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()));
java.util.List records = new java.util.ArrayList();
java.sql.ResultSet rs = selectestatement.executeQuery(query1);
while (rs.next()) {
java.util.List record = new java.util.ArrayList();
record.add(rs.getString("WHLO").trim());
record.add("888509018579");
record.add(rs.getString("ITEM_CODE").trim());
record.add(rs.getString("ARRIVAL_DATE").trim());
record.add(rs.getString("PAIRS_PER_CASE").trim());
record.add(rs.getString("ATS").trim());
records.add(record);
}
In this code, Final arraylist is the "records array". This records arraylist contents few record arrays.
How can i access the 1st element of record arraylist from the records arraylist?
Don't use raw types:
List<List<String>> records = new ArrayList<>();
List<String> record = new ArrayList<>();
...
records.add(record);
This way records.get(i) will return a List<String> instead of an Object, so you can access the elements of the inner List:
String first = records.get(0).get(0);
What you really want is a class containing your row data.
class RecordData {
public String whlo;
public long someNumber = 888509018579;
public String itemCode;
public String arrivalDate;
public String pairsPerCase;
public String ats;
}
and then do
java.util.List<RecordData> records = new java.util.ArrayList<>();
while (rs.next()) {
RecordData record = new RecordData();
record.whlo = rs.getString("WHLO").trim();
record.itemCode = rs.getString("ITEM_CODE").trim();
record.arrivalDate = rs.getString("ARRIVAL_DATE").trim();
record.pairsPerCase = rs.getString("PAIRS_PER_CASE").trim();
record.ats = rs.getString("ATS").trim();
records.add(record);
}
In fact, you want to make the members private and accessible via getters and setters, and use LocalDate for the arrivalDate and int for the pairsPerCase member, but the first point is not using a List to store the retrieved values but wrap it in a business-oriented class.
You can do something like this
((ArrayList)records.get(0)).get(0) to access the first element of the array list that is in the first position of the records array list.
Please note that if you specify what does the records contains (in this case records will contains array lists) then you won't need to cast the element to array list.
List<List<String>> records = new ArrayList<ArrayList>();
{...}
records.get(0).get(0); //You don't need the cast because Java already knows that what it is inside records are Lists
This function loops through a dictionary (allWords) and uses the
getKey function to generate a key. wordListMap is a HashMap> so I need to loop through and put the key and and a List. If there is not a list I put one if there is I just need to append the next dictionary word. This is where I need help. I just can't figure out the syntax to simply append the next word to the list that is already there. Any Help would be appreciated.
public static void constructWordListMap() {
wordListMap = new HashMap<>();
for (String w : allWords) {
int key = getKey(w);
if (isValidWord(w) && !wordListMap.containsKey(key)) {
List list = new ArrayList();
list.add(w);
wordListMap.put(key, list);
} else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
}
}
map.get(key).add(value)
Simple as that.
So I've gathered that you want to, given HashMap<Integer, List<String>>, you'd like to:
create a List object
add String objects to said List
add that List object as a value to be paired with a previously generated key (type Integer)
To do so, you'd want to first generate the key
Integer myKey = getKey(w);
Then, you'd enter a loop and add to a List object
List<String> myList = new List<String>;
for(int i = 0; i < intendedListLength; i++) {
String myEntry = //wherever you get your string from
myList.add(myEntry);
}
Lastly, you'd add the List to the HashMap
myHash.put(myKey, myList);
Leave any questions in the comments.
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
If you want to add a new value to your list, you need to retrieve that list first. In the code above, you are putting the return value of add into the table (which is a boolean), and that is not what you want.
Instead, you will want to do as Paul said:
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.get(key).add(w);
}
The reason this works is because you already added an ArrayList to the table earlier. Here, you are getting that ArrayList, and adding a new value to it.
Lets say you have an Iterator which will contains values that you need to compare with values that are located in a separate List.
Iterator<Map.Entry<String, Object>> it = aObj.items();
while (it.hasNext()) {
Map.Entry<String, Object> item = it.next();
nameValue = item.getNameValue();
keyValue = item.getKeyValue();
System.out.println("Name: " + nameValue);
System.out.println("Value: " + keyValue);
}
This outputs:
Name: header
Value: 22222
Lets say you have a separate list (in which you want to compare the above values with):
List<Items> items = new ArrayList<>();
for (Item item : items) {
itemNameValue = item.getName();
itemKeyValue = item.getKey();
System.out.println("Name: " + itemNameValue);
System.out.println("Value: " + itemKeyValue);
}
This outputs:
Name: header
Value: 44444
Since these are different types of loops (one is a while loop and the other one is a for each loop)
how can you compare for example:
if (nameValue.equals(itemNameValue())) {
// do something?
}
I need to iterate over both collections / data structures at the same time...
Would this be the solution?
String nameValue = "";
Object keyValue = "";
String itemNameValue = "";
String itemKeyValue = "";
Iterator<Map.Entry<String, Object>> it = aObj.items();
while (it.hasNext()) {
Map.Entry<String, Object> item = it.next();
nameValue = item.getNameValue();
keyValue = item.getKeyValue();
for (Item item : items) {
itemNameValue = item.getName();
itemKeyValue = item.getKey();
}
if (nameValue.equals(itemNameValue())) {
// do something?
}
}
Basically, what I am trying to ask (in a very simplified way is this):
(1) The collection that needs to be iterated in a while loop is just test input (sample data)
(2) The array list from the second collection is really a list of data which was returned from a database call (DAO) and placed into the ArrayList.
I am trying to verify if the input from Iterator inside the while loop is the same as the values from the ArrayList (which came from a database). Since these are different data structures requiring different looping mechanisms. How could I iterate through both data structures at the same time and compare them? The second data structure (the array list) is the actual set of values that are correct.
I don't know if there's a guarantee that each iteration would be comparing the same items if I use a nested loop?
Thank you for taking the time to read this...
The problem you are facing is a direct result of a BAD Application design.
The underline incorrect assumption of this question is that the map and the list will hold the objects in the same sequence.
List --> A data structure that is ordered by not sorted
Map --> A data structure that is neither ordered nor sorted
This is not to say that these two data structures don't work well together. However, using them to store the same list should only result from an awkward program design.
Even though to answer your question, you can use the below code to accomplish this:
Iterator<Map.Entry<String, Object>> it = aObj.items();
List<Items> items = dbCall.getItems(); // Get the list of Items from the DB
int index = 0;
while (it.hasNext()) {
Map.Entry<String, Object> itemFromMap = it.next();
Item itemFromList = items.get(index);
if(itemFromMap.getNameValue().equals(itemFromList.getName()) &&
itemFromMap.getKeyValue().equals(itemFromList.getKey())){
// If you prefer a single .equals() method over &&, then you can implement a Comparator<Item>
return false;
}
index++;
}
return true;