3

I learned that Advanced_For_Loop can take exactly two expressions. I don't know how it does work when it has three. I mean: for(expression1 : expression2 : expression3). And I don't know how it iterates in this code...

   private Sheet fieldVsTime(Workbook wb, String _title,List<PivotField>
   _pivots, List<PivotField> _all,boolean _periods,Map<String, String> 
   _yAxesMapping) {

    for (PivotField pivot : _all == null ? _pivots : _all) {
        List<PivotField> list = pivot.getPivot();
        if (list != null) {
            for (PivotField pivotField : list) {
                int publishDate = Integer.parseInt(pivotField.getValue().toString());
                if (_periods) {
                    publishDate = (publishDate / 10) * 10;
                }
                if (publishDate < minYear) {
                    minYear = publishDate;
                }
                if (publishDate > maxYear) {
                    maxYear = publishDate;
                }
            }
        }
    }
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
Ezz Eddin Othman
  • 163
  • 1
  • 12
  • 1
    Look at the `? :` ternary operator. – Dragonthoughts Jun 12 '18 at 12:45
  • 4
    *Enhanced* `for` loop, not *advanced* `for` loop. – T.J. Crowder Jun 12 '18 at 12:47
  • 2
    I wish the range-based for loop, a.k.a. foreach loop, wasn't colloquially called "enhanced" for loop. It's only enhanced with respect to pre-1.5 Java. It's enhanced in the sense that it now has two syntaxes instead of one. I prefer not to think of one syntax as being more enhanced than the other. – DodgyCodeException Jun 12 '18 at 13:02

2 Answers2

11

It only has two expressions:

for (PivotField pivot : (_all == null ? _pivots : _all))
     ----------------   -------------------------------
            1                       2

The second expression (_all == null ? _pivots : _all) returns either _pivots or _all, depending on whether or not _all == null.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

Equivalent to this code:

List<PivotField> pivotFields;
if( _all == null ) {
    pivotFields = _pivots;
}
else {
    pivotFields = _all;
}

for (PivotField pivot : pivotFields) {
    ...
}
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45