Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access outer scope variable from inside java lambda

Tags:

java

I am trying to loop through a result set and output the content. Using a lambda, I am able to output the keys I want, but in order to fetch the value I need to reference a variable on the scope. How can I reference a variable defined outside of a lambda expression..?

public static void SQLSelect(Connection c, String sql, String table) {
    ResultSet rs;
    Statement stmt;

    try {
        stmt = c.createStatement();
        rs = stmt.executeQuery("PRAGMA table_info(" + table + ")");
        ArrayList al = new ArrayList();
        while (rs.next()) {
            al.add(rs.getString("name"));
        }
        rs = stmt.executeQuery(sql + " FROM " + table);
        while (rs.next()) {
            al.forEach((item) -> {


                // complains here about local variable needing to be final
                System.out.println(item + ": " + rs.getString("address"));


            });
            System.out.println();
        }
        rs.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);

    }
}
like image 459
Billy Moon Avatar asked Apr 01 '26 16:04

Billy Moon


2 Answers

Variables used in lambdas have to be final or effectively final. rs is not effectively final because it is assigned twice. Simply replace the second version with another variable.

 ResultSet rs2 = stmt.executeQuery(sql + " FROM " + table);
    while (rs2.next()) {
        al.forEach((item) -> {


            // No longer complains
            System.out.println(item + ": " + rs2.getString("address"));


        });
        System.out.println();
    }
like image 52
Paul Boddington Avatar answered Apr 03 '26 14:04

Paul Boddington


The compiler is telling you that "rs" must be effectively final. That is, you only assign value to it once and don't change it's value throughout its scope. But you have to statements on which you assign a value to rs:

rs = stmt.executeQuery("PRAGMA table_info(" + table + ")");

and

rs = stmt.executeQuery(sql + " FROM " + table);
like image 42
Ulises Avatar answered Apr 03 '26 15:04

Ulises



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!