0

I am trying to convert the codes from native for loop to for each loop in lambda java 8. However, the index variable is not know. It is throwing an error that the variable must be final. The variable should increment as it creates dynamic data. How can I achieve it?

 List<MetadataObject> metadatas = new ArrayList<>();
    int index = 0;
        dataIDs.forEach(id -> {
            MetadataObject metadata = new MetadataObject();
            metadata.setTypeKey(id);
            metadata.setValue(metadataTypeValues.get(index));
            metadatas.add(metadata); // this is unknown
            index++; //this is unknown 
        });
Yejin
  • 541
  • 2
  • 15
  • 32
  • Just want to inform that the unknown variables are the list and the index. – Yejin Feb 28 '18 at 12:21
  • Was able to solve my problem by doing below. – Yejin Mar 01 '18 at 09:07
  • AtomicInteger index = new AtomicInteger(0); List metadatas = dataIDs.stream() .filter(id -> Objects.nonNull(id)) .map(id -> { MetadataObject metadata = new MetadataObject(); metadata.setTypeKey(id); metadata.setValue(metadataTypeValues.get(index.getAndIncrement()); }).collect(Collectors.toList()); – Yejin Mar 01 '18 at 09:07

0 Answers0