public class Java_03 {
public static void main(String[] args) {
List<Integer> listOfEven = Stream.iterate(1, i -> i+1)
.filter(i -> i % 2 == 0)
.limit(10)
.collect(Collectors.toList());
List<Integer> listOf3 = Stream.iterate(1, i -> i+1)
.filter(i -> i % 3 == 0)
.limit(10)
.collect(Collectors.toList());
// how to rewrite this code using lambdas and streams ?
Map<Integer, Integer> map = new TreeMap<>();
int i = 0;
for (int a : listOf3) {
map.put(listOfEven.get(i), a);
i++;
}
System.out.println(map);
}
}
我想用lambdas和stream编写这段代码我尝试了很多但是失败了。请帮忙。
map应该包含:key - 乘法表2和value - 乘法表3 例如 - {2 = 3,4 = 6,6 = 9,8 = 12,10 = 15,12 = 18,14 = 21,16 = 24,18 = 27,20 = 30}
答案 0 :(得分:0)
方法Collectors.toMap
可用于执行请求。
示例(计数保持计数器): -
int[] count = {0};
listOf3.stream().collect(Collectors.toMap(x->listOfEven.get(count[0]++), x->x))
运行示例: -
public static void main(String[] args) {
List<Integer> listOfEven = Stream.iterate(1, i -> i+1)
.filter(i -> i % 2 == 0)
.limit(10)
.collect(Collectors.toList());
List<Integer> listOf3 = Stream.iterate(1, i -> i+1)
.filter(i -> i % 3 == 0)
.limit(10)
.collect(Collectors.toList());
int[] count = {0};
System.out.println(listOf3.stream().collect(Collectors.toMap(x->listOfEven.get(count[0]++), x->x)));
}
答案 1 :(得分:0)
IntStream.range(0, listOf3.size()).forEach(i -> map.put(listOfEven.get(i), listOf3.get(i)));