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?
TolgarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TolgarAuthor Commented:
NOTE: I want to get the "value" of the key-value pair in the array of hashes.
0
mrcoffee365Commented:
Hi again.  Iterate over the arraylist, then get each object in the list and cast it to a hashmap.  Not sure why you created a new hashmap for each entry -- this means each hashmap has exactly 1 key-value pair, right?  Usually maps are for collections where you have to look them up by the key.  If there's only 1 element, there's no need for the hashmap collection.  Use a simple Array with 2 values in it.

However, with your above structures:

Iterator 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();
  }
 
}
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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

0
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

mrcoffee365Commented:
Right -- the only line to add to my sample code is the get on the val using the keyval which was just retrieved:

  Iterator iter = keysetString.iterator();
  while( iter.hasNext() ) {
    String keyVal = (String) iter.next();
    String valFromKey = amap.get(keyVal);
  }
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TolgarAuthor Commented:
@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,
0
mrcoffee365Commented:
Right.  Try using the code I posted.
0
TolgarAuthor Commented:
@mrcoffee365: Ok,but as I see in your code, I don't see any TreeItem. Should I make changes to your code?
0
TolgarAuthor Commented:
@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?
0
TolgarAuthor Commented:
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?
0
mrcoffee365Commented:
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.
0
TolgarAuthor Commented:
@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,
0
TolgarAuthor Commented:
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?
0
TolgarAuthor Commented:
ok. I cast it to integer instead.

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

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.