用lambda表达式替换for-each循环

时间:2018-04-24 16:45:26

标签: java foreach java-8 java-stream

我只是重构我的一些旧项目以使用Java 8的功能。

int counter = 1;
for (Checker checker : checkers) {
    if (counter < checkers.size()) {
        checker.setNextChecker(checkers.get(counter++));
    }
}

这里有点反应链模式。我需要为列表中的每个检查器设置下一个检查器,不包括最后一个检查器。

仍然无法在这里找到使用Stream API的方法:)

2 个答案:

答案 0 :(得分:5)

使用version: '2.2' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch-platinum:6.2.4 container_name: elasticsearch environment: - ELASTICSEARCH_USERNAME=elastic - ELASTICSEARCH_PASSWORD=MagicWord - cluster.name=docker-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 volumes: - esdata1:/usr/share/elasticsearch/data ports: - 9200:9200 networks: - esnet elasticsearch2: image: docker.elastic.co/elasticsearch/elasticsearch-platinum:6.2.4 container_name: elasticsearch2 environment: - ELASTICSEARCH_USERNAME=elastic - ELASTICSEARCH_PASSWORD=MagicWord - cluster.name=docker-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - "discovery.zen.ping.unicast.hosts=elasticsearch" ulimits: memlock: soft: -1 hard: -1 volumes: - esdata2:/usr/share/elasticsearch/data networks: - esnet kibana: image: docker.elastic.co/kibana/kibana:6.2.4 volumes: - ./kibana.yml:/usr/share/kibana/config/kibana.yml container_name: kibana environment: - KIBANA_ELASTICSEARCH_URL=elasticsearch - ELASTICSEARCH_USERNAME=elastic - ELASTICSEARCH_PASSWORD=MagicWord ports: - 5601:5601 networks: - esnet depends_on: - elasticsearch volumes: esdata1: driver: local esdata2: driver: local networks: esnet:

IntStream.range

或使用for循环:

IntStream.range(1, checkers.size())
         .forEach(i -> checkers.get(i-1).setNextChecker(checkers.get(i)));

答案 1 :(得分:1)

一个疯狂的选择:

Iterator<Checker> currentIt = checkers.subList(0, checkers.size() - 1).iterator();
Iterator<Checker> nextIt = checkers.subList(1, checkers.size()).iterator();
while (currentIt.hasNext()) {
  currentIt.next().setNextChecker(nextIt.next());
}

我猜你也可以用一个迭代器编写它:

Iterator<Checker> it = checkers.iterator();
Checker previous = it.next();
while (it.hasNext()) {
  previous.setNextChecker(previous = it.next());
}

但假设你的列表很小,RandomAccess,我只会坚持使用基于索引的循环:

for (int i = 0; i < checker.size()-1; ++i) {
  checkers.get(i).setNextChecker(checkers.get(i+1));
}

Streams在这里并不是一个好处。