如何在lambdas foreach块中更改外部方法的局部变量?

时间:2015-09-14 09:09:11

标签: java foreach lambda java-8

不适用于每个街区:

public void cleanup4(){
    long timestamp = Instant.now().minus(90l, ChronoUnit.DAYS)
            .toEpochMilli();
    String cql = "SELECT * FROM usertoken";
    ResultSet rs = CassandraTools.getInstance().execute(cql,ConsistencyLevel.QUORUM);
    CassandraConverter cassandraConverter=new MappingCassandraConverter();
    CassandraConverterRowCallback<UserTokenCassandra> callback= new CassandraConverterRowCallback<UserTokenCassandra>(cassandraConverter, UserTokenCassandra.class);
    UserTokenCassandra utc = null;
    Iterator<Row> iterator = rs.iterator();
    while (iterator.hasNext()) {
        Row row = iterator.next();
        utc=callback.doWith(row);
        log.info("{}", utc);
        log.info("记录的时间为:{}",
                Instant.ofEpochMilli(utc.getExpireTime()));
        if (timestamp > utc.getExpireTime()) {
            // repository.delete(n);
        }
    }
}

For-each block:

public void cleanup4(){
    long timestamp = Instant.now().minus(90l, ChronoUnit.DAYS)
            .toEpochMilli();
    String cql = "SELECT * FROM usertoken";
    ResultSet rs = CassandraTools.getInstance().execute(cql,ConsistencyLevel.QUORUM);
    CassandraConverter cassandraConverter=new MappingCassandraConverter();
    CassandraConverterRowCallback<UserTokenCassandra> callback= new CassandraConverterRowCallback<UserTokenCassandra>(cassandraConverter, UserTokenCassandra.class);
    rs.forEach(usertoken->{
        UserTokenCassandra utc = null;
        log.info("{}", utc);
        log.info("The Time:{}",
                Instant.ofEpochMilli(utc.getExpireTime()));
        if (timestamp > utc.getExpireTime()) {
            // repository.delete(utc);
        }
    });
}

1. for-each块似乎产生了很多没有使用UserTokenCassandra的引用..这些垃圾吗? 2.那么如何编写这段代码?

1 个答案:

答案 0 :(得分:1)

您无法在lambda体内修改外部方法局部变量。在这里,您不需要int[] array2 = array; 。作为forEach implements Iterable,您可以改为使用增强型ResultSet循环:

for