1

Question : from the list of an integer get the square of odd number and half the even number and then return the list of value.

Ans : 1> i will write the logic and if else condition inside the map() method.

List<Integer> output = intArray.stream().map(x-> {
                        if(x%2 ==0){
                            x=x/2;
                        }else{
                            x= x*x;
                        }
                     }).collect(Collectors.toList());

Is their any better way to do this specially using Filter?

Prabhat Yadav
  • 1,181
  • 6
  • 18
  • 29
  • Is this code compiling? You are not returning anything. And reassigning the incoming parameter has no effect for the caller. [Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – ernest_k Mar 15 '21 at 08:58
  • 3
    Filter is used to remove elements from a list. Since you want to perform operations on them, Map is the right way to go! – firstlegagain1 Mar 15 '21 at 09:01
  • 3
    `map(x -> x%2 == 0? x/2: x*x)` – Holger Mar 15 '21 at 09:11

2 Answers2

2

Try using map:

map(x -> x % 2 == 0? x / 2: x * x);

Let me know if this works for you.
You can learn more about map and filter here

Virej Dasani
  • 185
  • 3
  • 15
0

As you are transforming data (performing a math operation), you cannot use Filter here. Filter is used to filter out elements in your stream. For example if you only want to preserve the even numbers, you could use a Filter

What you need to use is the Map, as you already did. Do note that a map should always return data. Your code is missing this return statement.

To make it more readable, you could split your mapping logic in a method. This makes your stream easy to read and easy to follow (when you give the method a good name ofcourse).

Code example

List<Integer> output = intArray.stream()
            .map(test::divideOrPow)
            .collect(Collectors.toList());

private int divideOrPow(intx) {
    if (x % 2 == 0) {
        return x / 2;
    } else {
        return x * x;
    }
}
Yoni
  • 1,370
  • 7
  • 17