简体   繁体   中英

Java: How do I assign the first value in a for loop to the variable?

I have a List of type Info with member fields String and Map<String, Set<String>> . I need to iterate over the Set<String> s. Is it possible for me to assign the first Set<String> to a variable and perform operations on itself and the remaining values of each key ?

I'm new to Java, so this may not be properly articulated.

What I've tried. Given my scenario is understood, is using entrySet() correct here or will info.getInfoMap.values() suffice?

for (Info info : listOfInfo) {

      for (Map.Entry<String, Set<String>> entry : info.getInfoMap().entrySet()) {

        final Set<String> firstSetValue = entry.getValue();
        Set<String> set = entry.getValue();

        // do something to remaining sets with the first set
        // firstSetValue.equals(set)
        // firstSetValue.containsAll(set)


      }

Assuming those sets can't be null (and using var which is something you pretty much always want to use when iterating over entrySets):

Set<String> firstSet = null;

for (Info info : listOfInfo) {
   for (var entry : info.getInfoMap().entrySet()) {
       if (firstSet == null) firstSet = entry.getValue();
       // more here
    }
}

your code doesn't work: That firstSetValue = line is executed every loop. Making it final changes nothing: Variables in java spring into existence when you declare them and poof away when their 'scope' runs out, and java is scoped to the nearest {} . In other words, when the inner for loop loops, a new firstSetVariable poofs into existence, and then at the } that marks the end of the loop, it poofs away, and then assuming the loop loops once more, poof, there is an entirely new firstSetVariable . Thus, they don't 'remember' the first value, as they are entirely new, and marking them final makes no difference (it works fine: Their value indeed never changes, so they can be marked final. Instead the entire variable poofs out and back into existence every loop).

You just need to store the variable outside of the loop. Two approaches that immediately come to mind:

Set<Map.Entry<String, Set<String>> entrySet = info.getInfoMap().getEntrySet();
final Set<String> first = entrySet.iterator().next();

for (final Map.Entry<String, Set<String>> entry : entrySet) {
   ...
}

or

Set<String> first = null;

for (final Map.Entry<String, Set<String>> entry : info.getInfoMap().getEntrySet()) {
    if (first == null) {
        first = entry.getValue();
    }

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM