0

Could you tell me if there are other loop expressions which Java programmer must be able to read?

final List<String> names = Arrays.asList("Alice", "Bob", "Carol", "Dave", "Eve");

System.out.println("Pattern 1:");
for (int i = 0; i < names.size(); i++) {
    System.out.println(names.get(i));
}

System.out.println("Pattern 2:");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

System.out.println("Pattern 3:");
for (String name : names) {
    System.out.println(name);
}

System.out.println("Pattern 4:");
names.forEach(new Consumer<String>() {
    @Override
    public void accept(String name) {
        System.out.println(name);
    }
});

System.out.println("Pattern 5:");
names.forEach((String name) -> {System.out.println(name);});

System.out.println("Pattern 6:");
names.forEach((String name) -> System.out.println(name));

System.out.println("Pattern 7:");
names.forEach(name -> System.out.println(name));

System.out.println("Pattern 8:");
names.forEach(System.out::println);

System.out.println("Pattern 9:");
names.stream().forEach(System.out::println);
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
  • Try recursion as well. This might help: https://stackoverflow.com/questions/2044033/display-numbers-from-1-to-100-without-loops-or-conditions – Harry Joy Oct 09 '19 at 06:13
  • what's the difference between pattern 5, 6 and 7? It's just syntactical sugar. Are you looking up for patterns only? – Vinay Prajapati Oct 09 '19 at 06:15
  • @VinayPrajapati think Java programmer should know different syntax sugar, so I added them as different pattern. – Kohei TAMURA Oct 09 '19 at 06:21
  • Well! Remember when it comes to best coding practices and guidelines in effect most of these syntactic sugar should be avoided e.g. have a if block with curly braces always. Nonetheless it's good to know all of them. – Vinay Prajapati Oct 09 '19 at 06:24
  • 1
    All of 5, 6, 7, 8 can be used with or without `stream()` (like 9). – Dawood ibn Kareem Oct 09 '19 at 06:26

4 Answers4

2

Also we have,

names.stream().forEachOrdered(System.out::println);

forEachOrdered should be used instead of forEach because the behaviour of forEach is non-deterministic, but forEachOrdered performs the operations in the order defined in the stream, provided if you have defined an order in the stream

Also also, you have parallelStream, which can print the list irrespective of order,

names.parallelStream().forEach(System.out::println);

Alternatively you can also do, removing the first element after printing the list, you can do the same with iterators too, using iterator.previous method too.

while(!names.empty()){
    SOP(names.get(0));
    names = names.subList(1,names.size());
}
YouKnowWhoIAm
  • 334
  • 1
  • 12
1

Java 11

System.out.println("Pattern 11:");
names.forEach((var name) -> System.out.println(name));
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

You can use an iterator in a for loop:

for(Iterator<String> nameIterator = names.iterator(); nameIterator.hasNext(); ) {
    System.out.println(nameIterator.next());
}
Cwrwhaf
  • 324
  • 3
  • 5
1

Some more possibilities:

System.out.println("Pattern 12:");
IntStream.range(0, names.size())
        .mapToObj(i -> names.get(i))
        .forEach(System.out::println);

System.out.println("Pattern 13:");
Stream.generate(names.iterator()::next)
        .limit(names.size())
        .forEach(System.out::println);

But, rather than simply listing all of the looping patterns you can think of, it would be more useful to categorize them and think about the use cases for each one. As a start, I suggest these categories:

  1. Indexed loops, e.g. patterns 1, 12

    • use when you need an index (obviously)
    • also useful when you want to iterate through more than one loop at a time
    • you can also have additional terminating conditions
  2. Non-indexed, breakable loops, e.g. patterns 2, 3

    • more readable than indexed loops when you don't need an index
    • use when you need other terminating conditions (e.g. when searching for a specific value in a list)
  3. Non-indexed, non-breakable loops, e.g. patterns 4, 9, 13:

    • can be the most readable kind in certain cases (but certainly not all)
    • use when you readily have a lambda or method reference and you don't need an index, don't need to process more than one collection together, and don't need to break out early
    • in Java 11, (well, to be precise, from Java 9 onwards, but who on earth still uses Java 9 nowadays), patterns 9 and 13 fall into the breakable category using the new takeWhile method.
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42