How we get the List objects in backward direction? - java

Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table data in reverse order. mean that, for ex
i am adding some rows to particular table in database when i am added recently, the data is storing at last row in table(in database). here i have to show whole content of the table in my jsp page in reverse order, mean that what i inserted recently have to display first row in my jsp page.
here my code was like,
List lst = tabledate.getAllData();//return List<Table> Object
Iterator it = lst.iterator();
MyTable mt = new MyTable();//pojo class
while(it.hasNext())
{
mt=(MyTable)it.next();
//getting data from getters.
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
}

Use a ListIterator to iterate through the list using hasPrevious() and previous():
ListIterator it = lst.listIterator(lst.size());
while(it.hasPrevious()) {
System.out.println(it.previous());
}

You cannot use an iterator in this case. You will need to use index based access:
int size = lst.size();
for (int i=size - 1; i >= 0; i --)
{
MyTable mt = (MyTable)lst.get(i);
....
}
Btw: there is no need to create a new MyTable() before the loop. This is an instance that will be thrown away immediately and serves no purpose.

Related

updating particular item in list

I have an list of customer object. I need to read them from shared preferences and check for particular object by id with my new object and replace the old one in list with new object and write it to back to pref. This is what I am doing..Is it right?
List<School> schools = readFromPref();
ListIterator<School> iterator = schools.listIterator();
while (iterator.hasNext()) {
School oldSchool = iterator.next();
if (oldSchool.getId().equalsIgnoreCase(newSchool.getId())) {
iterator.set(newSchool);
schools.add(newSchool);
}
}
writeToPref(schools);
Remove schools.add(newSchool); because iterator.set(newSchool); is updating your school list already.
And everything looks good
You can use Enhanced For loop to get and update data in your ArrayList.
ArrayList<School> schools = readFromPref();
int i=0;
for(School oldSchool : schools){ //Enhanced For loop
if(oldSchool.getId().equalsIgnoreCase(newSchool.getId())){
oldSchool.setId(newSchool.getId());
schools.set(i, oldSchool);
}
i++;
}
writeToPref(schools);
Here is the link of how to save and retrive Object from SharedPreference using Gson.
Store your data in form of map where key will be the id of your object,and update the object on key basis

How to convert a list of objects to a multi-dimensional array

I have a list of objects (result from a select query), I want to convert it into an array and I want to put each column of the query in a column in the array. I have tried many solutions in the forum but I haven't found a solution.
In my bean I have the following list:
private List<PhBonCmd> listEntree; // The PhBonCmd is an object model imported has attributes like codeprod , quant ,...
.....
String sql ="select c.codeprod as codeprod , c.quant as quant ,c.date_cmd as date_cmd, c.date_expir as date_expir,c.numbco as numbco, c.auteur as auteur,"
+"c.idcmd as idcmd ,f.nomfourn as nomfourn ,coalesce(c.quant_livre, 0) as quant_livre ,m.libelle as libelle "
+"from commandes c,listeproduit m,fournisseur f "
+"where c.codeprod=m.codeproduit and c.fourn=f.idfourn and c.statut='IN' and c.numbco ='"+getNumbco()+"' ";
listEntree = (List<PhBonCmd>) this.bcService.execRequete(sql);//Here the results of the sql query
Now what I want is to put each column of the List (listEntree) in a multidimensional arraylist, so as if I want to access to a specific single value in of the arraylist, I do so.
I want to put the results of the query in an array and from there , i want to access to elements of the array . Have things like this array1[row][col]
Why are you casting to List<PhBonCmd>? . The ResultSet is by default multidimensional. If you want to convert to a multidimensional List, you can do it by processing the ResultSet.
If you are using Spring , you can use RowMapper or ResultSetExtractor to get the desired behaviour.
I don't know the reason of doing that, when you have OOP power, but here it is.
You have to use reflection to get know fields (lets say columns if you wish) of PhBonCmd on fly:
Class clazz = PhBonCmd.class;
Field[] fields = clazz.getFields();
String[][] myDemensionalArray = new String[fields.length()][listEntree.size()];
for(int i=0; i < fields.length(); i++){
for(int j=0; j < listEntree.size(); j++){
myDemensionalArray[i][j] = fields[i].get(listEntree.get(j));
}
}

Get individual values from an array created from a resultset in java

I have an array that was created from an ArrayList which was in turn created from a ResultSet. This array contains rows of database table and each row (with several columns based on my query) exists as a single element in the array. So far so good. My problem is how to get individual values (columns) from each row which, I said earlier, now exists as an element. I can get each element (row, of course) but that is not what I want. Each element is a composite of several values and how to get those? I am a beginner and really stuck here. I think this all make sense. Here's the code how I created the array.
List resultsetRowValues = new ArrayList();
while (resultSet.next()){
for (int i = 1; i <= columnCount; i++) {
resultsetRowValues.add(resultSet.getString(i));
}
}
String[] databaseRows = (String[]) resultsetRowValues.toArray(new String[resultsetRowValues.size()]);
EDIT: More explanation
My MySQL query is as follows:
String query = "SELECT FIRSTNAME, LASTNAME, ADDRESS FROM SOMETABLE WHERE CITY='SOMECITY'";
This returns several rows in a ResultSet. And according to the sample query each element of an array will cotain three values (columns) i.e FIRSTNAME, LASTNAME and ADDRESS. But these three values exist in the array as a single element. While I want each column separately from each element (which is actually a row of the database table). When I iterate through the aarray using for loop and print the values to the console, I get output similar to the following:
Doe
Jhon
Some Street (End of First element)
Smith
Jhon
Some Apartment (End of Second element and so on)
As it is evident from the output, each element of the contains three values which are printed on separate lines.
How to get these individual values.
You probably want something like that:
List<Map<String, String>> data = new ArrayList<>();
while (resultSet.next()){
Map<String, String> map = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
map.put("column" + i, resultSet.getString(i));
}
data.add(map)
}
// usage: data.get(2).get("column12") returns line 3 / column 12
Note that there are other possible options (2D-array, guava Table, ...)

Get data from table using jSoup

I am looking to get data from the table on http://www.sportinglife.com/greyhounds/abc-guide using jSoup. I would like to put this data into some kind of table within my java program that I can then use in my code.
I'm not too sure how to do this. I have been playing around with jSoup and currently am able to get each cell from the table to print out using a while loop - but obviously can't use this always as the number of cells in the table will change.
Document doc = Jsoup.connect("http://www.sportinglife.com/greyhounds/abc-guide").get();
int n = 0;
while (n < 100){
Element tableHeader = doc.select("td").get(n);
for( Element element : tableHeader.children() )
{
// Here you can do something with each element
System.out.println(element.text());
}
n++;
}
Any idea of how I could do this?
There are just a few things you have to implement to achieve your goal. Take a look on this Groovy script - https://gist.github.com/wololock/568b9cc402ea661de546 Now lets explain what we have here
List<Element> rows = document.select('table[id=ABC Guide] > tbody > tr')
Here we're specifying that we are interested in every row tr that is immediate child of tbody which is immediate child of table with id ABC Guide. In return you receive a list of Element objects that describes those tr rows.
Map<String, String> data = new HashMap<>()
We will store our result in a simple hash map for further evaluation e.g. putting those scraped data into the database.
for (Element row : rows) {
String dog = row.select('td:eq(0)').text()
String race = row.select('td:eq(1)').text()
data.put(dog, race)
}
Now we iterate over every Element and we select content as a text from the first cell: String dog = row.select('td:eq(0)').text() and we repeat this step to retrieve the content as a text from the second cell: String race = row.select('td:eq(1)').text(). Then we just simply put those data into the hash map. That's all.
I hope this example with provided description will help you with developing your application.
EDIT:
Java code sample - https://gist.github.com/wololock/8ccbc6bbec56ef57fc9e

While loop won't stop looping Java

I have created simple table called Reservations and this table have following columns: ID, DUE_DATE, PRODUCTS_PAID, RESERVATION_NAME, SALE, TOTAL_SELL_PRICE and CUSTOMER_ID.
Now what I want to do is that I want to iterate through this table where CUSTOMER_ID is given value. Here is my method that collects all those columns data by CUSTOMER_ID:
public Collection<Reservations> findReservation(int cuID) {
EntityManager em = getEntityManager();
Query q = em.createQuery("SELECT r FROM Reservations r WHERE r.customerData.id = :cID");
q.setParameter("cID", cuID);
List results = q.getResultList();
return results;
}
My problem here is that whenever I run iteration loop it won't stop iterating but it continues to iterate. I have only two rows of data in that table. Can you tell me why this iteration continues and won't stop? Obviously I just want to iterate all data inside of that table based on given CUSTOMER_ID value.
I have tried for loops, for each loops and while loops and non of them works. It must be something to do with my code. Here is one while loop that I tested but it won't stop iteration like the rest loops:
for(Iterator itr2 = rd.findReservation(cuID).iterator(); itr2.hasNext();){
rModel.addRow(Arrays.asList(rd.findReservation(cuID).iterator().next().getId(),
rd.findReservation(cuID).iterator().next().getReservationName(),
rd.findReservation(cuID).iterator().next().getCustomerData().getCustomerName(),
rd.findReservation(cuID).iterator().next().getCustomerData().getCustomerType(),
rd.findReservation(cuID).iterator().next().getDueDate(),
rd.findReservation(cuID).iterator().next().getTotalSellPrice(),
rd.findReservation(cuID).iterator().next().getSale(),
rd.findReservation(cuID).iterator().next().getProductsPaid(),
"Print"));
}
If you wonder what is cuID, its just an integer value which is received from table column. This value is customerID. It works well. So it shouldn't effect on the code. All help is appreciated :)
Because you don't call the next on your iterator that you have declared in the loop. Try this instead :
for(Iterator itr2 = rd.findReservation(cuID).iterator(); itr2.hasNext();){
MyObject obj = itr2.next();
rModel.addRow(Arrays.asList(obj.getId(),
obj.getReservationName(),
obj.getCustomerData().getCustomerName(),
obj.getCustomerData().getCustomerType(),
obj.getDueDate(),
obj.getTotalSellPrice(),
obj.getSale(),
obj.getProductsPaid(),
"Print"));
}
You need to do something like this:-
for(Reservations res : rd.findReservation(cuID)){
// Do whatever you want with this object(res)
rModel.addRow(Arrays.asList(res.getId(), res.getReservationName()...);
}
This is clean and simple! No need to use iterator in that weird way you've used, which just keeps getting a new iterator and keeps fetching the first entry from that, hence leading to an infinite loop!
you use two separate iterators. What you do is this:
while (iterator1.hasNext()) {
iterator2.next();
}
obviously you won't exhaust iterator1. Use the same iterator in your loop and in rModel line:
Iterator it = rd.findReservation(cuID).iterator();
while (it.hasNext()) {
// or whatever your type is
Object next = it.next();
rModel.addRow(Arrays.asList(next.getId(),
next.getReservationName(),
next.getCustomerData().getCustomerName(),
next.getCustomerData().getCustomerType(),
next.getDueDate(),
next.getTotalSellPrice(),
next.getSale(),
next.getProductsPaid(),
"Print"));
}

Categories