在 Java 8 中使用 Streams 而不是 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41661931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:33:55  来源:igfitidea点击:

Using Streams instead of for loop in java 8

javajava-8java-stream

提问by Sarang Shinde

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

I have above code where I have used for loop and double and triple the numbers and stored it in different arrays in single loop. Can anybody help me to write the same code using streams with its map and other methods without iterating numbers array twice.

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

采纳答案by thegauravmahawar

You can do it like this:

你可以这样做:

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

回答by Darshan Mehta

You can use streamwith forEachmethod to populate collectionsof doubles and triples e.g.:

您可以使用streamwithforEach方法来填充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);
}

Another example with mapand collect:

另一个例子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);
}

回答by jon-hanson

You can apply the doubling and tripling within the stream:

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

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

though technically that's still iterating over the array twice.

虽然从技术上讲,它仍然在数组上迭代两次。

As a trick you could instead collect the results in a Map:

作为一个技巧,您可以改为在 Map 中收集结果:

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

回答by eg04lt3r

Seems like your question is more complicated than just using Java Stream API. The better way is define some wrapper class like Num.class:

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

class Num {
    private final int value;

    //constructor

    public int powerOf(int index) {
        return Math.pow(value, index);
    }

}

Then you can just wrap your array elements into this object and call powerOfmethod where you need. With your implementation you are creating unnecessary arrays for keeping powered values. And using Stream API in this case is more convinient:

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

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