List comprehensions: Difference between revisions
Content added Content deleted
(Updated Java code to use IntStreams to do the list comprehension bit. Technically cleaner, but still clunky.) |
|||
Line 957: | Line 957: | ||
Using list-of-arrays made the syntax easier than list-of-lists, but meant that you need the "output expression" part to get to something easily printable. |
Using list-of-arrays made the syntax easier than list-of-lists, but meant that you need the "output expression" part to get to something easily printable. |
||
<lang Java>// Boilerplate |
<lang Java>// Boilerplate |
||
import java.util.ArrayList; |
|||
import java.util.Arrays; |
import java.util.Arrays; |
||
import java.util.List; |
import java.util.List; |
||
import java.util. |
import static java.util.function.Function.identity; |
||
import static java.util.stream.Collectors.toList; |
|||
⚫ | |||
import static java.util.stream.IntStream.range; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
System.out.println(run(20)); |
System.out.println(run(20)); |
||
} |
} |
||
Line 968: | Line 969: | ||
static List<List<Integer>> run(int n){ |
static List<List<Integer>> run(int n){ |
||
return |
return |
||
// Here comes the list comprehension bit |
// Here comes the list comprehension bit |
||
// input stream - bit clunky |
|||
range(1, n).mapToObj( |
|||
x -> range(x, n).mapToObj( |
|||
y -> range(y, n).mapToObj( |
|||
z -> new Integer[]{x, y, z} |
|||
) |
|||
) |
|||
) |
|||
.flatMap(identity()) |
|||
.flatMap(identity()) |
|||
// predicate |
// predicate |
||
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) |
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) |
||
// output expression |
// output expression |
||
.map( |
.map(Arrays::asList) |
||
// the result is a list |
// the result is a list |
||
.collect( |
.collect(toList()) |
||
; |
|||
} |
} |
||
} |
} |