1

I have a 2-D array of ints, and a method with an argument that points to one of its rows. I want to return a Set over the elements of that row that are non-zero, and I want to do it without a for loop. So this is what I have tried:

public Set<Integer> getNeighbors(int node) {
        assert node >= 0 && node < numNodes : "getNeighbors(): Invalid node parameter given: " + node + ".";
       return Arrays.stream(matrix[node]).filter(n->n>0).collect(Collectors.toSet());
    }

Unfortunately, I'm getting a compile-time error which is a bit hard to parse:

A Screenshot from my IDE

Any ideas?

Naman
  • 27,789
  • 26
  • 218
  • 353
Jason
  • 2,495
  • 4
  • 26
  • 37

2 Answers2

5
return Arrays.stream(matrix[node])
             .filter(n -> n > 0)
             .boxed()
             .collect(Collectors.toSet());

will do it. The .boxed() bit is the relevant part.

Naman
  • 27,789
  • 26
  • 218
  • 353
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
2

You are trying to create Set with int primitives, (Arrays.stream "returns a sequential IntStream with the specified Array as its source") and a Set<int> is not allowed. You want to add in a boxed() to convert the IntStream to a Stream<Integer>:

public Set<Integer> getNeighbors(int node) {
    assert node >= 0 && node < numNodes : "getNeighbors(): Invalid node parameter given: " + node + ".";
    return Arrays.stream(matrix[node])   //IntStream
                 .filter(n->n>0)   
                 .boxed()                //Convert to Stream<Integer>
                 .collect(Collectors.toSet());
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45