【问题标题】:How to rewrite this code using lambdas and streams?如何使用 lambdas 和流重写此代码?
【发布时间】:2016-06-23 10:14:42
【问题描述】:
 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 和流来编写这段代码。请帮忙。

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}

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您上面的代码已经使用了 lambdas 和流。它不工作吗?您还想达到什么目标?
  • 无法在评论中粘贴我的代码!
  • @KushalMaharana 只需编辑您的问题
  • 注释中的代码应该使用 lambda 和流来完成。

标签: java lambda java-stream


【解决方案1】:

方法Collectors.toMap可以用来做请求。

Sample(计数持有计数器):-

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)));
         }

【讨论】:

  • 这种对数组的滥用是一种不鼓励的代码风格。除此之外,此代码生成未指定类型的地图,而不是TreeMap
【解决方案2】:
IntStream.range(0, listOf3.size()).forEach(i -> map.put(listOfEven.get(i), listOf3.get(i)));

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 1970-01-01
  • 2021-05-06
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
相关资源
最近更新 更多