Java 8 Mapping( 映射)练习题

来源:互联网 发布:软件发明专利范文 编辑:程序博客网 时间:2024/06/15 03:53

1.给定一个数字列表, 如何返回每个数字的平方列表?例如, 给定 [1、2、3、4、5], 您应该返回 [1、4、9、16、25]。
Given a list of numbers, how would you return a list of the square of each number?For example, given [1, 2, 3, 4, 5] you should return [1, 4, 9, 16, 25].

List<Integer> number1=Arrays.asList(1,2,3,4,5);List<Integer> number2=number1.stream().map(n->n*n).collect(toList());number2.forEach(System.out::println);

2.给定两个数字列表, 如何返回所有对数字?例如, 给定一个列表 [1, 2, 3] 和一个列表 [3, 4] 你应该返回 [(1, 3), (1, 4), (2, 3), (2, 4), (33), (3, 4)]。为了简单起见, 可以将一对作为具有两个元素的数组表示。
Given two lists of numbers, how would you return all pairs of numbers? For example,given a list [1, 2, 3] and a list [3, 4] you should return [(1, 3), (1, 4), (2, 3), (2, 4), (3,3), (3, 4)]. For simplicity, you can represent a pair as an array with two elements.

List<Integer> number3=Arrays.asList(1,2,3);List<Integer> number4=Arrays.asList(3,4);List<int[]> parms=number3.stream()                .flatMap(i->number4.stream()                        .map(j->new int[]{i,j}))                .collect(toList());parms.forEach(pair -> System.out.println("[" + pair[0] + ", " + pair[1] + "]"));

3.如何扩展前面的示例以返回其总和可被3整除的对?例如, (2、4) 和 (3、3) 是有效的。
How would you extend the previous example to return only pairs whose sum is divisible by 3? For example, (2, 4) and (3, 3) are valid.

import java.util.*;import static java.util.stream.Collectors.toList;public class Filtering{    public static void main(String...args){        List<Integer> number3=Arrays.asList(1,2,3);        List<Integer> number4=Arrays.asList(3,4);        List<int[]> parms1=number3.stream()                .flatMap(i->number4.stream()                        .filter(j->(i+j)%3==0)                        .map(j->new int[]{i,j}))                .collect(toList());        parms1.forEach(pair -> System.out.println("[" + pair[0] + ", " + pair[1] + "]"));    }}
原创粉丝点击