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
  • 21,685
  • 24
  • 196
  • 332
Jason
  • 2,048
  • 2
  • 23
  • 31

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
  • 21,685
  • 24
  • 196
  • 332
rzwitserloot
  • 65,603
  • 5
  • 38
  • 52
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,630
  • 4
  • 27
  • 42