How to save the ArrayList> from return fu

2019-08-28 01:23发布

问题:

I'm not so familiar with manipulating ArrayList<HashMap<String, String>>. In this problem I want to save the return ArrayList<HashMap<String, String>> from a function. However, I don't know weather if I code it wrong. Can anyone help me?

I've check my sql code, it work pretty fine and return the things that I want.

List<HashMap<String, String>> ErrorList= new ArrayList<HashMap<String, String>>();
ErrorList = select("SELECT * FROM process_result WHERE (status = 'Error') AND (mailBefore = 'No');");
public List<HashMap<String, String>> select(String query) {
        List<HashMap<String, String>> output = new ArrayList<HashMap<String, String>>();

        HashMap<String, String> map = null;
        Statement statement = null;
        try {
            statement = this.conn.createStatement();
            ResultSet rs = statement.executeQuery(StringEscapeUtils.unescapeJava(query));

            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();

            map = new HashMap<String, String>();

            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++ ) {
                    map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                output.add(map);
            }

        } catch (SQLException e) {
            logger.error(e);
            e.printStackTrace();
        }
        //System.out.print("This is select output:" + output);
        return output;
    }

The code don't correctly save the return value from select function.

回答1:

You are overwriting the keys of the map with same column name and data for each row in the same map instance all the time, so you would end up with the data of the last row from the ResultSet in the map and the output list will have only one entry

Instead create a new HashMap instance for every row in the ResultSet and add the map to the list for each row:

while (rs.next()) {
   map = new HashMap<>(); //create one new map for every row
   for (int i = 1; i <= columnCount; i++ ) {
        map.put(rsmd.getColumnName(i), rs.getString(i));
   }
   output.add(map);
}

Also I suggest changing the signature of the method to:

public List<Map<String, String>> select(String query)

So you do not couple your code to an implementation.

You would need to change these lines as well:

List<Map<String, String>> output = new ArrayList<Map<String, String>>();
// do not have a dependency on a particular implementation of the Map API
Map<String, String> map = null; 


标签: java jdbc