Jump to content

List comprehensions: Difference between revisions

Updated Java code to use IntStreams to do the list comprehension bit. Technically cleaner, but still clunky.
(Updated Java code to use IntStreams to do the list comprehension bit. Technically cleaner, but still clunky.)
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.
<lang Java>// Boilerplate
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.streamfunction.CollectorsFunction.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 classinterface PythagComp{
public static void main(String[]... args){
System.out.println(run(20));
}
Line 968 ⟶ 969:
static List<List<Integer>> run(int n){
return
 
// Here comes the list comprehension bit
// input stream - bit clunky
 
//range(1, input list - bit clunkyn).mapToObj(
new ArrayList<Integer[] x -> range(x, n){{.mapToObj(
for(int x=1; x<n; x++ y -> range(y, n).mapToObj(
for(int y= z -> new Integer[]{x;, y<n;, y++)z}
for(int z=y; z<n; z++)
add(new Integer[]{x,y,z});
}}.stream()
.flatMap(identity())
 
.flatMap(identity())
// predicate
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
 
// output expression
.map(a -> Arrays.::asList(a))
 
// the result is a list
.collect(Collectors.toList());
;
}
}
Cookies help us deliver our services. By using our services, you agree to our use of cookies.