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.stream.Collectors;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
public class PythagComp{
import static java.util.stream.IntStream.range;
public static void main(String[] args){
public interface PythagComp{
static void main(String... args){
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

// input list - bit clunky
range(1, n).mapToObj(
new ArrayList<Integer[]>(){{
x -> range(x, n).mapToObj(
for(int x=1; x<n; x++)
y -> range(y, n).mapToObj(
for(int y=x; y<n; y++)
z -> new Integer[]{x, y, z}
for(int z=y; z<n; z++)
)
add(new Integer[]{x,y,z});
)
}}.stream()
)
.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(a -> Arrays.asList(a))
.map(Arrays::asList)

// the result is a list
// the result is a list
.collect(Collectors.toList());
.collect(toList())
;
}
}
}
}