Table of Contents
Example
usage instructions
algorithm
Output
Use stream(), filter() and reduce() methods
Home Java javaTutorial Java program to find maximum odd number in array using stream and filter

Java program to find maximum odd number in array using stream and filter

Sep 09, 2023 pm 07:49 PM
filter flow Maximum odd number

Java program to find maximum odd number in array using stream and filter

In this section, we will write a Java program to find the largest odd number in an array using streams and filters. Odd numbers are numbers that are not divisible by "2", or the remainder is 1 when divided by "2". In other words, it can be written in the form ‘2n 1’. We will find the largest odd number in the array.

Example

Input: array = {1, 7, 2, 3, 9, 5, 10}
Output: Maximum odd number is 9
Copy after login

From the above example, the largest odd number in the array is 9.

Input: array = {11, 17, 12, 13, 19, 15, 20}
Output: Maximum odd number is 19
Copy after login

From the above example, the largest odd number in the array is 19.

usage instructions

stream() - It is used to create a stream of elements so that we can use methods such as filter(), map(), reduce(), etc. to process the data

Arrays.stream(collection)	
Copy after login

filter() - Used to filter data in a stream, i.e. select specific elements from the stream based on conditions. It returns a boolean value.

treamobject.filter(condition)	
Copy after login

reduce() - Used to reduce the number of elements and return a single result number based on a binary operation.

Streamobject.reduce(initial value, binary operation)	
Copy after login

We will now discuss different ways to find the largest odd number in an array using streams and filters (implemented using code in Java).

algorithm

  • Initialize the array and use the stream() method to create a stream for the array

  • Use filter method() and parameters as conditions to filter the stream to filter out odd numbers from the array.

  • Use the max() method to return the largest odd number. If there is no odd number, use the orElse() method to print -1.

Example

In this example, we first initialize an array. Then we use the "stream()" method to convert the array into a stream, then use the "filter()" method on the stream to filter out the odd numbers present in the stream, and on the resulting stream we use the max() method to find all odd numbers in the stream the maximum value. If there are no odd numbers in the stream, we use the "orElse" function to return the value of the input parameter. Then we print the value stored in the "maximumOdd" variable.

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int[] array = {1, 7, 2, 3, 9, 5, 10};
      int maximumOdd = Arrays.stream(array)
      .filter(n -> n % 2 != 0)
      .max()
      .orElse(-1);
      System.out.println("Maximum odd number is: " +maximumOdd);
   }
}
Copy after login

Output

Maximum odd number is: 9	
Copy after login

Use stream(), filter() and reduce() methods

  • Initialize the array and use the stream() method to create a stream for the array

  • Use filter method() and parameters as conditions to filter the stream to filter out odd numbers from the array.

  • Use the reduce() method to find the largest odd number

  • Use the ternary operator to print the largest odd number, or -1 if there is no odd number.

Example

In this example, we first initialize an array. Then we use the "stream()" method to convert the array into a stream, then use the "filter()" method on the stream to filter out the odd numbers present in the stream, and on the resulting stream we use the reduce() method to find all odd numbers in the stream the maximum value. If there are no odd numbers in the stream, the MaximumOdd number contains Integer.MIN_VALUE. We then use the ternary operation ‘?’ and check if the ‘maximumOdd’ variable contains Integer.MIN_VALUE. If it contains Integer.MIN_VALUE, then we print -1, otherwise we print the value stored in the "maximumOdd" variable.

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int[] array = {1, 7, 2, 3, 9, 5};
      int maximumOdd = Arrays.stream(array)
      .filter(n -> n % 2 != 0)
      .reduce(Integer.MIN_VALUE, Integer::max);
      System.out.println("Maximum odd number in the given array is   " + (maximumOdd != Integer.MIN_VALUE ? maximumOdd : -1));
   }
}
Copy after login

Output

Maximum odd number in the given array is   9
Copy after login

So, in this article, we have discussed how to find the maximum odd number in an array using different methods using streams and filters in Java.

The above is the detailed content of Java program to find maximum odd number in array using stream and filter. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue error: The filter in filters cannot be used correctly, how to solve it? Vue error: The filter in filters cannot be used correctly, how to solve it? Aug 26, 2023 pm 01:10 PM

Vue error: The filter in filters cannot be used correctly, how to solve it? Introduction: In Vue, filters are a commonly used function that can be used to format or filter data. However, during use, sometimes we may encounter problems with not being able to use the filter correctly. This article will cover some common causes and solutions. 1. Cause analysis: The filter is not registered correctly: Filters in Vue need to be registered before they can be used in templates. If the filter is not successfully registered,

In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs Sep 14, 2023 am 10:37 AM

The FILTER_VALIDATE_URL constant is used to validate URLs. The flag FILTER_FLAG_SCHEME_REQUIRED−URL must be RFC compliant. FILTER_FLAG_HOST_REQUIRED−URL must contain the hostname. FILTER_FLAG_PATH_REQUIRED−URL must have a path after the domain name. FILTER_FLAG_QUERY_REQUIRED−URL must have a query string. Return value FILTER_VALIDATE_URL

Filter function in Vue3: handle data elegantly Filter function in Vue3: handle data elegantly Jun 18, 2023 pm 02:46 PM

Filter Functions in Vue3: Handling Data Elegantly Vue is a popular JavaScript framework with a large community and a powerful plug-in system. In Vue, the filter function is a very practical tool that allows us to process and format data in templates. There have been some changes to the filter functions in Vue3. In this article, we will take a deep dive into the filter functions in Vue3 and learn how to use them to handle data gracefully. What is a filter function? In Vue, the filter function is

How to filter and sort data in Vue technology development How to filter and sort data in Vue technology development Oct 09, 2023 pm 01:25 PM

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

PHP Email Filter: Filter and identify spam. PHP Email Filter: Filter and identify spam. Sep 19, 2023 pm 12:51 PM

PHP Email Filter: Filter and identify spam. With the widespread use of email, the amount of spam has also continued to increase. For users, the amount of spam they receive can lead to information overload and wasted time. Therefore, we need an efficient method to filter and identify spam emails. This article will show you how to write a simple but effective email filter using PHP and provide specific code examples. Basic Principle of Email Filter The basic principle of email filter is to determine whether the email is

Tips for using plug-ins to implement custom filters in Vue Tips for using plug-ins to implement custom filters in Vue Jun 25, 2023 pm 05:01 PM

Tips for using plug-ins to implement custom filters in Vue Vue.js provides a convenient way to handle the need for view data filtering, that is, filter. Filters are mainly responsible for formatting and processing the data in the view to make the data more intuitive and easy to understand. Vue has some built-in commonly used filters, such as date formatting, currency formatting, etc., and also supports custom filters. This article will introduce how to use the Vue plug-in to implement custom filters and provide some practical filtering techniques.

Several methods to solve Tomcat garbled code Several methods to solve Tomcat garbled code Dec 28, 2023 pm 01:32 PM

Several methods to solve the problem of Chinese garbled characters in Tomcat, which require specific code examples. In web development, we often encounter the problem of Chinese garbled characters in Tomcat. This problem will cause garbled characters or appear as boxes, question marks and other characters when processing Chinese characters, bringing a bad experience to users. In order to solve this problem, this article will introduce several commonly used methods and provide specific code examples. Modify the Tomcat configuration file. Find the conf/server.xml file in the Tomcat installation directory and search for the default

Python Logging Module Revealed: A Deep Dive into Its Capabilities Python Logging Module Revealed: A Deep Dive into Its Capabilities Feb 21, 2024 am 09:30 AM

The pythonLogging module is a powerful tool for managing application logging. It provides a flexible and configurable framework that enables developers to control the generation, processing, and display of log information. Logging Levels The Logging module defines several logging levels to specify the importance of log messages. These levels are ordered in increasing severity: DEBUG: Used for debugging and development purposes, logging detailed debugging information. INFO: Logs general application information such as events and operations. WARNING: Logs potential problems or exceptions that do not necessarily interrupt the application. ERROR: Logs a serious error or exception that may cause application failure. CRITICAL: Records in danger

See all articles