2

I have a List of matches. A match has a property called matchIndex. Now I want to set the property of each match in list like this

index = 0 // some predefined value

List<Match> matchList = createMatches(membersList, teamsPerGroup,totalGroups);
    matchList.forEach((match) -> {
    match.setMatchIndex(index++);
});

I want to set matchIndex of each match in the list by increasing order after local variable index.

2
  • final int index = 0; Commented Apr 20, 2019 at 5:41
  • I think a final value can't be changed Commented Apr 20, 2019 at 5:47

2 Answers 2

3

You can't use this because variables in lambda should be final or effectively final. you can follow this code:

IntStream.range(0, matchList .size())
            .mapToObj(index -> {
                Match match= list.get(index);
                match.setMatchIndex(index);
                return match;
            })
            .collect(Collectors.toList());

or use AtomicInteger

AtomicInteger index= new AtomicInteger(1);
matchList.forEach(match-> match.setMatchIndex(index.getAndAdd(1)));

UPDATE:

As @Holger commented The correct solution is

IntStream.range(0, matchList.size()) 
         .forEach(index -> matchList.get(index) .setMatchIndex(index));

and if you want to use some predefined value this is right solution:

 IntStream.range(0, matchList.size()) 
          .forEach(index -> matchList.get(index) .setMatchIndex(index + offset));
Sign up to request clarification or add additional context in comments.

6 Comments

What if I want to start the index from some predefined value?
go with second approach.
The correct solution is in-between: IntStream.range(0, matchList.size()) .forEach(index -> matchList.get(index) .setMatchIndex(index)); And, by the way, why do you initialize the AtomicInteger with one, contradicting every other example?
@Holger, Thanks for your feedback. OP commented What if I want to start the index from some predefined value? so I though second way was for it.
I see. So you should make it clear right in the answer, that this is addressing an additional point (as readers should not be required to read the comments to understand an answer). Of course, that would work with the canonical solution too: IntStream.range(0, matchList.size()) .forEach(index -> matchList.get(index) .setMatchIndex(index + offset));
|
0

Actually, there is a lazy way to do it but it's not the Java 8 way. Still, I am posting this answer:)

int index = 0; // starting index

for (Match match: matchList) {
    match.setMatchIndex(matchIndex++);
}

Hope it helps.

Comments

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.