11

I have the following problem. I have an integer position which starts at 1 and increments every time a specific person from a txt is found at a specific position in an xml. If I use the classic iteration with the foreach for (PersonMatchInfo pmi : personMatchInfo) it works, but my senior asked me to do with the Java 8 foreach and this type of iteration works only with final variables. How can I increment the integer in the new Java 8 loop? Thank you.

int position = 1;
personMatchInfo.forEach(pmi ->{

                    if (!stopwatch1.isStarted()) {
                        stopwatch1.start();
                    } else if (stopwatch1.isStarted()) {

                    }

                    if (pmi.getPersonName().equals(e.getValue())) {

                        positionMap.put(position, positionMap.get(position) + 1);
                        break;

                    } else {

                        position++;
                    }
                });
10
  • 9
    by telling your senior: "that is not a reasonable request, it needlessly takes up time, is more complex and it is less readable. And I do not know how to do it because final blah blah blah, can you please help me!?" Commented Oct 2, 2017 at 8:41
  • 1
    (It would not reduce the time consumed by the code - it would not perform better than a classical foreach loop.) Commented Oct 2, 2017 at 8:44
  • 3
    Ask your senior if he is familiar with the term "premature optimization". Commented Oct 2, 2017 at 8:45
  • 3
    @Fildor Can we add "K.I.S.S" while we're at it? Commented Oct 2, 2017 at 8:46
  • 1
    @Bilkokuya I think we could even find some more if we tried. Commented Oct 2, 2017 at 8:46

4 Answers 4

20

You can use AtomicInteger, and incrementAndGet method on it.

Other solution would be int[] position = new int[]{1};

and incrementing position[0]++;

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

6 Comments

It works with the array but it is reducing the runtime whatsoever. Still the same. :(
what do you mean by reducing the runtime? You will not gain performance by switching from for_each loop, to collection.forEach
Right now i am trying to reduce the duration of the run in my code. My senior gave me the "hint" to use lambda foreachs because they are java 8 based and stuff.
awful hint. Try sampling/profiling your code with jvisualvm
org.apache.commons.lang3.mutable.MutableInt is more appropriate.
|
2

You can use a static variable :

public class Poubelle {

    private static int position = 1;

    public static void setPosition (List<PersonMatchInfo> listPersonMatchInfo) {

          listPersonMatchInfo.forEach(pmi -> {
          pmi.setPosition(position++);
        });
    }
}

1 Comment

Ironically, using a static int is what worked for me. I had a pair of nested lambda functions, and I needed to pass on the count of the inner lambda function into its contents. Since the outer lambda function needed to re-set the variable to zero every time it ticked over, I just did a position = 0; (to use your example) before the inner lambda function. Haven’t yet tested, but intellisense is not having a hissy fit.
0

I think you senior is asking you to use streams for collections. Then use collection.stream.filter.count based on your logic that will produce a long as the value and use it.

3 Comments

no the downvoter, but that sounds like an utter abuse of the filter method and only works by coincidence.
Thanks bro for your answer
I was initially thinking the same as Mark, and I think map filter count it's a perfectly valid case for counting instead of modifying a global state counter although I read the question again and I don't think a count operation is needed here as this is building a map with positions.
0

I know it is late, so I will just put it out here for future seekers. Here is how you can do it in a very simple way :

use indexOf(Object O) property of collections

StringBuffer messageBody = new StringBuffer();    
List<VipObj> listOfAllVips = getResponse();
    listOfAllVipsLocal.forEach(vip -> {
                            messageBody.append("\n\t" + (listOfAllVipsLocal.indexOf(vip) + 1) + ". " + vip.getBaseUrl() + "\n");
                        });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.