16
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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Sarang Shinde
  • 717
  • 3
  • 7
  • 24

5 Answers5

35

You can do it like this:

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

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<Integer, Integer> m = Arrays.stream(numbers)
        .boxed()
        .collect(Collectors.toMap(
                x -> x * 2,
                x -> x * 3
        ));
jon hanson
  • 8,722
  • 2
  • 37
  • 61
  • 1
    Yes Jon thats right its simpler and clean approach that i am aware of but yes i am expecting to iteration of array only once – Sarang Shinde Jan 15 '17 at 14:23
  • @SarangShinde I've edited my answer to add another solution which avoids iterating over the array twice. – jon hanson Jan 15 '17 at 14:43
  • 1
    Iterating twice shouldn’t be a problem as the question’s code is iterating *three* times, so the error is already in the question. Accepting an answer that “solves” this by simply omitting one of the two requested results (besides changing “times” to “power”), is quite strange. – Holger Jan 16 '17 at 09:40
2

Seems like your question is more complicated than just using Java Stream API. The better way is define some wrapper class like 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. With your implementation you are creating unnecessary arrays for keeping powered values. And using Stream API in this case is more convinient:

Arrays.stream(numbers).map(Num::new)
        .forEach(n -> System.out.println("power of 2": + n.powerOf(2));
eg04lt3r
  • 2,467
  • 14
  • 19
1

You can use stream with forEach method to populate collections of doubles and triples e.g.:

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:

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);
}
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

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