Java Program to Find Maximum Odd Number in Array Using Stream and Filter
Java 8 introduced some great features like Stream and Filter which tremendously simplify tasks like reading data and performing operations like minimum, maximum, sum, and conditional check on them. In this program, we will get the maximum of all odd numbers from a list of integers with the help of the Java Stream and Filter method.
Using Loops
In the absence of Streams, we could achieve the given task by iterating through the list and checking if the number is odd. If true, we would check if it is larger than the maximum odd number until now.
Below is the implementation of the approach:
Java
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
class GFG {
public static int maxOdd(List<Integer> list)
{
Iterator<Integer> it = list.iterator();
int max = 0 ;
while (it.hasNext()) {
int num = it.next();
if (num % 2 == 1 ) {
if (num > max) {
max = num;
}
}
}
return max;
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 11 );
list.add( 43 );
list.add( 56 );
list.add( 82 );
list.add( 51 );
list.add( 29 );
list.add( 10 );
System.out.println( "Largest odd number: "
+ maxOdd(list));
}
}
|
Output
Largest odd number: 51
Using Stream and Filter
Stream filter returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Below is the implementation of the above approach:
Java
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
class GFG {
public static int maxOdd(List<Integer> list)
{
return list.stream()
.filter(n -> n % 2 == 1 )
.max(Integer::compare)
.orElse( 0 );
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 11 );
list.add( 43 );
list.add( 56 );
list.add( 82 );
list.add( 51 );
list.add( 29 );
list.add( 10 );
System.out.println( "Largest odd number: "
+ maxOdd(list));
}
}
|
Output
Largest odd number: 51
Performance Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Last Updated :
29 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...