codemoonger
codemoonger

Reputation: 663

Interate over char array with another int array using streams

I want to use streams in java like LINQ in .net. I have two arrays one is a char array and the other is int array. Now I looping with a foreach loop to print a message using the two arrays, one hold the chars and the other is just the positions where to pick the char.

Here is the code:

char[] letter = {115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 119, 105, 110, 100, 103, 32 };
int[] pos = {0,1,2,3,4,5,6,7,8,9,10,5,11,16,12,0,16,4,12,13,15};

for(int s:pos){
    System.out.print(letter[s]);
}

I want to make this using streams.

My idea was to do something like this.

Arrays.asList(
    0,1,2,3,4,5,6,7,8,9,10,5,11,16,12,0,16,4,12,13,15
)
.stream()
.forEach(p -> p)

So in the lambda expression in the forEach use the letter char array but maybe now but it straight in like

letter[p]

Upvotes: 1

Views: 119

Answers (1)

vszholobov
vszholobov

Reputation: 2363

You can do it with map and access by index

public static void main(String[] args) {
    char[] letter = {115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 119, 105, 110, 100, 103, 32 };
    int[] pos = {0,1,2,3,4,5,6,7,8,9,10,5,11,16,12,0,16,4,12,13,15};

    Arrays.stream(pos).map(x -> letter[x]).forEach(System.out::print);
}

Output:

11511697991071111181011141021081111193210511532107105110103

If you don't want to create int[] array you can use Stream.of()

Stream.of(0,1,2,3,4,5,6,7,8,9,10,5,11,16,12,0,16,4,12,13,15)
      .map(x -> letter[x])
      .forEach(System.out::print);

But output would be

stackoverflow is king

The difference appears because in the first example the stream was started from an int array and chars later converted to int. if you want to display the word in the first example, then replace the stream with

Arrays.stream(pos)
      .mapToObj(x -> (char) letter[x])
      .forEach(System.out::print);

Upvotes: 2

Related Questions