【问题标题】:Using Streams instead of for loop in java 8在 java 8 中使用 Streams 而不是 for 循环
【发布时间】:2017-01-15 13:58:59
【问题描述】:
int [] numbers = {1,2,3,4,5,6,7,8};
int [] doubleNumbers = new int[numbers.length];
int [] tripleNumbers = new int[numbers.length];


for(int index = 0; index < numbers.length; index++)
{
    doubleNumbers[index] = numbers[index] * 2;  
    tripleNumbers[index] = numbers[index] * 3;
}

System.out.println("Double Numbers");
Arrays.stream(doubleNumbers).forEach(System.out::println);

System.out.println("Triple Numbers");
Arrays.stream(tripleNumbers).forEach(System.out::println);

我在上面的代码中使用了 for 循环,并将数字加倍和加倍,并将其存储在单个循环中的不同数组中。任何人都可以帮助我使用流及其映射和其他方法编写相同的代码,而无需两次迭代数字数组。

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    你可以这样做:

    IntStream.range(0, numbers.length)
      .forEach(index -> {
        doubleNumbers[index] = numbers[index] * 2;
        tripleNumbers[index] = numbers[index] * 3;
      });
    

    【讨论】:

    • 嗨 Gaurav,这个选项很棒,我一直在寻找,但它适用于上述情况,但如果我使用 int [] numbers = {11,22,33,44,55,66,77, 88};这个数组作为输入它的失败和抛出异常你能告诉我如何驾驭它吗?
    • @SarangShinde 之前有一个错误,现在已修复。
    【解决方案2】:

    您可以在流中应用加倍和三倍:

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
    
        System.out.println("Double Numbers");
        Arrays.stream(numbers).map(x -> x * 2).forEach(System.out::println);
    
        System.out.println("Triple Numbers");
        Arrays.stream(numbers).map(x -> x * 3).forEach(System.out::println);
    }
    

    虽然从技术上讲,它仍然会遍历数组两次。

    作为一种技巧,您可以将结果收集到 Map:

    Map<Integer, Integer> m = Arrays.stream(numbers)
            .boxed()
            .collect(Collectors.toMap(
                    x -> x * 2,
                    x -> x * 3
            ));
    

    【讨论】:

    • 是的,乔恩就是这样,我知道它更简单、更干净的方法,但是是的,我希望数组只迭代一次
    • @SarangShinde 我已经编辑了我的答案以添加另一个解决方案,以避免两次迭代数组。
    • 迭代两次应该不是问题,因为问题的代码是迭代三次次,所以错误已经在问题中了。接受一个通过简单地省略两个请求结果之一来“解决”这个问题的答案(除了将“时间”更改为“功率”),这很奇怪。
    【解决方案3】:

    似乎您的问题比仅使用 Java Stream API 更复杂。更好的方法是定义一些包装类,如Num.class:

    class Num {
        private final int value;
    
        //constructor
    
        public int powerOf(int index) {
            return Math.pow(value, index);
        }
    }
    

    然后你可以将你的数组元素包装到这个对象中并在你需要的地方调用powerOf 方法。通过您的实现,您正在创建不必要的数组来保持动力值。在这种情况下使用 Stream API 更方便:

    Arrays.stream(numbers).map(Num::new)
            .forEach(n -> System.out.println("power of 2": + n.powerOf(2));
    

    【讨论】:

    • 感谢您的快速响应和对同一问题的不同看法。
    【解决方案4】:

    您可以使用 streamforEach 方法来填充 collections 的双精度和三倍,例如:

    public static void main(String[] args) {
        int [] numbers = {1,2,3,4,5,6,7,8};
        List<Integer> doubles = new ArrayList<Integer>();
        List<Integer> triples = new ArrayList<>();
    
        Arrays.stream(numbers)
        .boxed()
        .forEach(n -> {
            doubles.add(n*2);
            triples.add(n*3);
            }
        );
    
        System.out.println(doubles);
        System.out.println(triples);
    }
    

    mapcollect 的另一个示例:

    public static void main(String[] args) {
        int [] numbers = {1,2,3,4,5,6,7,8};
    
        List<Integer> doubles = Arrays.stream(numbers)
        .boxed()
        .map(n -> n*2)
        .collect(Collectors.toList());
    
        List<Integer> triples = Arrays.stream(numbers)
                .boxed()
                .map(n -> n*3)
                .collect(Collectors.toList());
    
        System.out.println(doubles);
        System.out.println(triples);
    }
    

    【讨论】:

      【解决方案5】:

      您可以将每个 number 表示为 doubletriple 数字的字符串数组,然后使用单个流输出这些数组:

      int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
      
      Arrays.stream(numbers)
              // represent each number as a string
              // array of double and triple numbers
              // Stream<String[]>
              .mapToObj(i -> new String[]{
                      String.valueOf(i * 2),
                      String.valueOf(i * 3)})
              // reduce a stream of arrays to a single array
              .reduce((arr1, arr2) -> new String[]{
                      // concatenate double numbers
                      arr1[0] + " " + arr2[0],
                      // concatenate triple numbers
                      arr1[1] + " " + arr2[1]
              }) // output values if present
              .ifPresent(arr -> {
                  System.out.println("Double numbers: " + arr[0]);
                  System.out.println("Triple numbers: " + arr[1]);
              });
      

      输出:

      Double numbers: 2 4 6 8 10 12 14 16
      Triple numbers: 3 6 9 12 15 18 21 24
      

      另见:Generate all possible string combinations by replacing the hidden # number sign

      【讨论】:

        猜你喜欢
        • 2020-05-19
        • 2023-01-13
        • 1970-01-01
        • 2020-08-14
        • 2013-07-05
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 2012-01-27
        相关资源
        最近更新 更多