jeudi 22 novembre 2018

Arrays.stream() vs. .stream(), when to use which one [duplicate]

This question already has an answer here:

So I am trying to understand how to use streams, but I can't figure out how you're supposed to create a stream.

For Example:

public void printMultiRandom(int howMany)
{
    int[] nums = rand.ints(howMany).toArray();
    Arrays.stream(nums)
        .forEach(number -> System.out.println(number));

}

This code is correct and working, but I don't know why I have to use Arrays.stream(nums) as opposed to this:

public void printMultiRandom(int howMany)
{
    int[] nums = rand.ints(howMany).toArray();
    nums.stream()
        .forEach(number -> System.out.println(number));

}

I know that there are even more ways to create streams, like stream.of(), but I don't know what situations you're supposed to use them in.

Edit:

Okay so I think I now somewhat understand why nums.stream() doesn't work in this case. Because the .stream() method is only a method of collections, and int[] = nums is an array and not a collection. If this is the case, is there an easier way for me to code this. The Random method ints() says that it returns an IntStream already, can I use this without converting it to an array, and how would I go about doint that?




Aucun commentaire:

Enregistrer un commentaire