0

I Used a HashMap for handling my ResultSet queried from PostgreSql using the code suggested by RHT

public List resultSetToArrayList(ResultSet rs) throws SQLException{
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    ArrayList list = new ArrayList(50);

    while (rs.next()){
        HashMap row = new HashMap(columns);
        for(int i=1; i<=columns; ++i){           
            row.put(md.getColumnName(i), rs.getObject(i));
        }
        list.add(row);
    }

    return list;
}

I did it beacuse I wanted to shuffle this collection afterwards.

now each row is like that:

  {owner=22172613@N07, count=2}

I do not know how I can do a for/each loop that I retrieve each owner id and corresponding number !!

Community
  • 1
  • 1
GeoBeez
  • 920
  • 2
  • 12
  • 20
  • 1
    Can you post your table structure? You might not need to call `getObject`. – Tim Biegeleisen Nov 08 '16 at 10:47
  • Don't use raw types but use interfaces for collections! `Map row = new HashMap<>(columns)`. After that, examine if you really need to put an `java.lang.Object` into your map or if you may have some other datatype... – Markus L Nov 08 '16 at 10:54
  • @ Tim Biegeleisen what I get as result set is the list of my users and the number of images that each have in my system. – GeoBeez Nov 08 '16 at 12:07

1 Answers1

3

So you have an ArrayList each element of which is a HashMap that contains in its key the column names of the results and in its values the values of those columns.

A loop that will most probably help you is the following:

    //call your method resultSetToArrayList here
     List<Map> list = (List<Map>) resultSetToArrayList(rs);

    //loop the list
    for(Map r: list) {
        System.out.println("row data: ");
        final Iterator columnIterator = r.keySet().iterator();
        while(columnIterator.hasNext()) {
            final Object next = columnIterator.next();
            System.out.println("\tColumn: " + next + " / Value: " + r.get(next));
        }
    }
pleft
  • 7,567
  • 2
  • 21
  • 45
  • but still it is not possible to compare it with string ` if (next.toString() == "owner") { printDebug(next +""+userImages.get(next) ); owner = userImages.get(next).toString(); }` – GeoBeez Nov 08 '16 at 11:34
  • that's another problem not mentioned in your initial question. You asked for a loop to retrieve the values, well here it is, expand it more to do what you want. Can you post what the loop prints? – pleft Nov 08 '16 at 12:35
  • the problem was I used `if (next =="owner")` but the correct version is `next.equals("owner")` – GeoBeez Nov 08 '16 at 14:22
  • I just realized that with this solution some of the key values are missing! do you know why it's happening! – GeoBeez Nov 08 '16 at 23:59
  • it was just because of forgetting closing the buffer for writer! – GeoBeez Nov 09 '16 at 10:02