0

How i can write this code in Java 8?

for (Iterator<RecordVo> iterator = list.iterator(); iterator.hasNext();) {
            RecordVo recordVo = (RecordVo) iterator.next();         
            ExecutionContext singleThreadExecutionContext = new ExecutionContext();
            singleThreadExecutionContext.put("customerId", recordVo.getCustomerId());
            singleThreadExecutionContext.put("ThreadName", "Thread-"+recordVo.getCustomerId());
            multiThreadExecutionContext.put("Partition - "+recordVo.getCustomerId(), singleThreadExecutionContext);
        }
5
  • Why do you need to? What's wrong with this code? Commented Aug 24, 2017 at 19:16
  • I am learning Java8 and trying to modify my existing code to 8 lambda. Got stuck at this code snippet. I tried using stream, collect, collectors but unable to move forward Commented Aug 24, 2017 at 19:19
  • See, learning a tool means also learning where that tool is useful and where it is not. In this case, streams are not a useful tool. You'll get far more mileage by using for(each : ofList) here than from streams, and that's Java 6. Commented Aug 24, 2017 at 19:23
  • Thanks, that is helpful. Commented Aug 24, 2017 at 19:24
  • I was trying something like this list.forEach(recordVo->multiThreadExecutionContext.put("Partition - "+recordVo.getCustomerId(),new ExecutionContext().put("customerId", recordVo.getCustomerId()))); Commented Aug 24, 2017 at 19:29

1 Answer 1

1

How about the following?

list.stream()
  .map(RecordVo::getCustomerId)
  .map(id -> {
    // create singleThreadExecutionContext as before
    return new SimpleImmutableEntry(id, singleThreadExecutionContext);
  })
.forEach(e -> multiThreadExecutionContext.put("Partition - " + e.getKey(), e.getValue()))

I didn't compile it, but you can do that.

Sign up to request clarification or add additional context in comments.

1 Comment

It compiled and worked like a charm. Only modification i did is casting e.getValue to ExecutionContext. . (ExecutionContext)e.getValue() I am using the old way in my code but it is really helpful to know how to do it in Java 8. Thanks Abhijit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.