0

I'm trying to convert old-style for loop with some newly generated variables and if statements int the new style using java streams and lambda expression.

    for (MyClass a : list_1) {
      if (a.myMethod() != null) {
        List<Integer> list_2 = myMap.get(/*some code*/);                 
        if (list_2 == null) {
          list_2 = new ArrayList<>();
          myMap.put(/*some code*/);
        }
        list_2.add(/*some code*/);
      }
    }

1 Answer 1

2

Let's take a closer look to the different parts.

First you need a stream:

list_1.stream()

Next you have an if. This can most of the time be converted into filter:

.filter(a -> a.myMethod() != null)

Then, you want to do some things with your data. you can use forEach for that:

list_1.stream()
  .filter(a -> a.myMethod() != null)
  .forEach(a -> {
    // only put list in if absent
    myMap.putIfAbsent(/* your stuff */);
    myMap.get(/* some code */).add(/* your stuff */);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Where should I create list_2 ? @christian-wörz
Where you need it. I think you just put it inside your map and then get it from your map.

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.