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?
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.
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.
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);
}
IntStream provides a sequence of primitive int-valued elements which seems is what you need. This may be more efficient than boxing the values.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.You have several errors :
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>.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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With