简体   繁体   English

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

[英]Using Streams instead of for loop in java 8

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.我有上面的代码,我在其中使用了 for 循环,并将数字加倍和三倍,并将其存储在单循环中的不同数组中。 Can anybody help me to write the same code using streams with its map and other methods without iterating numbers array twice.任何人都可以帮助我使用流及其映射和其他方法编写相同的代码,而无需重复数字数组两次。

You can do it like this:你可以这样做:

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

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

Seems like your question is more complicated than just using Java Stream API.似乎您的问题比仅使用 Java Stream API 更复杂。 The better way is define some wrapper class like Num.class :更好的方法是定义一些包装类,如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 powerOf method where you need.然后你可以将你的数组元素包装到这个对象中,并在你需要的地方调用powerOf方法。 With your implementation you are creating unnecessary arrays for keeping powered values.通过您的实现,您正在创建不必要的数组来保持幂值。 And using Stream API in this case is more convinient:在这种情况下使用 Stream API 更方便:

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

You can use stream with forEach method to populate collections of doubles and triples eg:您可以使用带有forEach方法的stream来填充双精度和三倍的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 map and 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);
}

You can represent each number as a string array of double and triple numbers, and then output those arrays using a single stream:您可以将每个数字表示为双数三重数的字符串数组,然后使用单个流输出这些数组:

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

Output:输出:

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

See also: Generate all possible string combinations by replacing the hidden # number sign另请参阅:通过替换隐藏的#数字符号生成所有可能的字符串组合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM