Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad operand types for binary operator '%' [duplicate]

Tags:

java

list

java-8

I am trying to code the java 8 way:

public static void main (String[] args) throws java.lang.Exception
{
    int arr [] =  {3,4,5,6,7};

    Arrays.asList(arr)
          .stream()
          .filter(i -> i % 2)
          .sorted()
          .map(j -> j+ 1)
          .forEach(System.out::println);

}

filter is supposed to pretty much throw away odd numbers but I get the below error.

Main.java:16: error: bad operand types for binary operator '%'
              .filter(i -> i % 2)
                             ^
  first type:  int[]
  second type: int
Main.java:18: error: bad operand types for binary operator '+'
              .map(j -> j+ 1)
                         ^
  first type:  int[]
  second type: int

Can someone please explain the cause of this error?

like image 547
Tilak Maddy Avatar asked Dec 29 '16 09:12

Tilak Maddy


People also ask

What is bad operand types for binary operator?

Bad operand types for binary operator '&&' Explanation: This issue occurs because (x/2) is a numeric expression that returns an integer value. Therefore, the logical AND operator is known as &&. As a result, it anticipates boolean values on both sides.

What is binary operator in Java?

Interface BinaryOperator<T>Represents an operation upon two operands of the same type, producing a result of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of the same type.


2 Answers

Your desired code may look like this:

public static void main (String[] args) throws java.lang.Exception {
    int arr [] =  {3,4,5,6,7};
    IntStream.of(arr)
          .filter(i -> i % 2 == 0)
          .sorted()
          .map(j -> j+ 1)
          .forEach(System.out::println);
}
  1. IntStream provides a sequence of primitive int-valued elements which seems is what you need. This may be more efficient than boxing the values.
  2. The filter in this case needs an int predicate. It should return true or false as in the example code above. Your lambda is not a predicate because it returns an integer.
like image 166
Lachezar Balev Avatar answered Sep 24 '22 16:09

Lachezar Balev


You have several errors :

  1. Arrays.asList() for a primitive array returns a List whose single element is that array. Therefore the elements of your Stream are arrays instead of integers. You should change int arr [] = {3,4,5,6,7} to Integer arr [] = {3,4,5,6,7}, in order to get a List<Integer>.
  2. filter takes a Predicate, i.e. a method that returns boolean. Therefore filter(i -> i % 2) should be filter(i -> i % 2 == 0) (if you want to keep the even numbers) or filter(i -> i % 2 == 1) (if you want to keep the odd numbers).
like image 33
Eran Avatar answered Sep 22 '22 16:09

Eran