Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to loop through an array of hashes in Java?

Hi,
I have the following code to read some data from a database.

    public List<HashMap<Integer, String>> getFullCheckList() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver") ;
        Connection conn = DriverManager.getConnection("jdbc:mysql://someserver/somedatabase", "somedatabase", "pwd") ;
        Statement stmt = conn.createStatement() ;
        String querycheckName = "SELECT `name` FROM `check`;" ;
        ResultSet rs = stmt.executeQuery(querycheckName) ;
        ArrayList<HashMap<Integer, String>> checkList = new ArrayList<HashMap<Integer, String>>();
        while(rs.next()) {
            HashMap<Integer, String> check = new HashMap<Integer, String>();
            check.put(rs.getInt(0), rs.getString(1));
            checkList.add(check);
        }
        rs.close();
        stmt.close();
        conn.close();
        
        return checkList;
    } 

Open in new window


Then I use the following code to create a tree structure using the data that I gathered from the database.

However, the part of the code that I marked as "THIS PART SHOULD CHANGE" is not right, because checkList is now an array of hashes which has the "id" and "name" pair. (It used to be ResultSet before I changed my code. That's why I have checkList.next in here)

    public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList) throws SQLException {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                    }
                }
            });
                  
           //////THIS PART SHOULD CHANGE  - START
            while( checkList.next() ) {
                String myval1 = checkList.getString("name");
                  TreeItem itemI = new TreeItem(tree, SWT.NONE);
                  itemI.setText("Check " + myval1);
          }
          //////THIS PART SHOULD CHANGE  - END

    } 

Open in new window


So, how should I change that part so that I can get the name part of the "id" and "name" pair, and create the tree with the data that I have in checkList?
Avatar of Tolgar
Tolgar

ASKER

NOTE: I want to get the "value" of the key-value pair in the array of hashes.
SOLUTION
Avatar of mrcoffee365
mrcoffee365
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I agree with mrcoffee about NOT using a HashMap for this. Although I would probably suggest to create a new class to represent the id,name pair. The other way to go is (I am assuming here that the "id" values from the database are unique?) is to just use a HashMap by itself, not a list of hashmaps, where the one HashMap holds the id, name pairs.

However, if you are going with the current structure, mrcoffee code is not quite what you want. That will retrieve the id part of the pair, ie. the key of the key-value. Try something like this...
for (HashMap<Integer, String> check : checkList) {
    String myval1 = check.values.iterator.next;
    TreeItem itemI = new TreeItem(tree, SWT.NONE);
    itemI.setText("Check " + myval1);
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tolgar

ASKER

@mccarl: I am using mccarl's code as it is and I see an error on line 2 for the "values".

String myval1 = check.values.iterator.next;

Open in new window


The error message says: The field AbstractMap<Integer,String>.values is not visible

Why does this happen and how can I fix it?

Thanks,
Right.  Try using the code I posted.
Avatar of Tolgar

ASKER

@mrcoffee365: Ok,but as I see in your code, I don't see any TreeItem. Should I make changes to your code?
Avatar of Tolgar

ASKER

@mrcoffee365: ok. I made this little change in your code:

            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter .hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                String keyVal = (String) iter.next();
                String valFromKey = amap.get(keyVal);
                  TreeItem itemI = new TreeItem(tree, SWT.NONE);
                  itemI.setText("Check " + valFromKey);
              } 
            }

Open in new window


but I am getting this error now:

Exception in thread "main" java.lang.NullPointerException

what could this be?
Avatar of Tolgar

ASKER

ok. I found why I got this error.

In the following line where I call a method to create the tree, compTab2 is null

But it shouldn't be null. I use it many other places in this file. but it is null in here. (This code is in gui.java file)

        CheckListTree clt = CheckListTree.getInstance();
        clt.createCheckListTree(compTab2, checksGridData2, checkList);

Open in new window


This is the beginning of the class I have createCheckListTree method:
public class CheckListTree {
    private Tree tree;
    private static CheckListTree instance = null;
   
    
    private CheckListTree()
    {
        if (instance == null) {
            instance = new CheckListTree();
         }
    }
    
    public static CheckListTree getInstance()
    {
        return instance;
    }

Open in new window


And this is the createCheckListTree method in this class (in CheckListTree.java file):

   
public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList)  {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                    }
                }
            });
                  
            
            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter .hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                String keyVal = (String) iter.next();
                String valFromKey = amap.get(keyVal);
                  TreeItem itemI = new TreeItem(tree, SWT.NONE);
                  itemI.setText("Check " + valFromKey);
              } 
            }
    }  

Open in new window


Can you see the problem in this code?
It looks as if you're handling an event from the user in the method as well as populating the dropdown list for the display for the user.

So -- when the dropdown list is being populated, there isn't an event yet.  So the comptab2 is null?

Not sure.

In any case, you could check if comptab2 is null, and not execute the code with it in that case.
Avatar of Tolgar

ASKER

@mrcoffee365: I fixed the null pointer exception error and now the code can go into createCheckListTree method but when it comes to the code that you recommended I get the following error:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at com.something.tools.something.something.CheckListTree.createCheckListTree(CheckListTree.java:88)

Open in new window


The createCheckListTree method is like this and line 88 is line 22 below:

    public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList)  {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                    }
                }
            });
                  
            
            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter .hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                String keyVal = (String) iter.next();
                String valFromKey = amap.get(keyVal);
                  TreeItem itemI = new TreeItem(tree, SWT.NONE);
                  itemI.setText("Check " + valFromKey);
              } 
            }
    } 

Open in new window


Do you know why this casting does not work and what should do instead?

Thanks,
Avatar of Tolgar

ASKER

Now, I fixed this problem by replacing:

String keyVal = (String) iter.next();

Open in new window


with

String keyVal = iter.next().toString();

Open in new window


but now, when I print "valFromKey" it is all "null".

How will I get the value of the key-value pair?
Avatar of Tolgar

ASKER

ok. I cast it to integer instead.

Integer keyVal = (Integer) iter.next();

Open in new window