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 implementation to find // the maximum odd number in array import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
class GFG {
// Function to find the maximum
// odd number in array
public static int maxOdd(List<Integer> list)
{
// Iterator for accessing the elements
Iterator<Integer> it = list.iterator();
int max = 0 ;
while (it.hasNext()) {
int num = it.next();
// Adding the elements
// greater than 5
if (num % 2 == 1 ) {
if (num > max) {
max = num;
}
}
}
return max;
}
// Driver Code
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));
}
} |
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 implementation to find // the maximum odd number // in the array import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
class GFG {
// Function to find the maximum odd
// number in the list
public static int maxOdd(List<Integer> list)
{
// Converted to Stream
// Filtering the odd number
// Taking maximum out of those integers
return list.stream()
.filter(n -> n % 2 == 1 )
.max(Integer::compare)
.orElse( 0 );
}
// Driver Code
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));
}
} |
Largest odd number: 51
Performance Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)