Java stream условие если

Как использовать if/else Logic в Java 8 Streams

В этом руководстве мы собираемся продемонстрировать, как реализовать логику if / else с Java 8Streams. В рамках этого руководства мы создадим простой алгоритм для определения четных и нечетных чисел.

Мы можем взглянуть наthis article, чтобы понять основы Java 8Stream.

2. Обычная логикаif/else в пределахforEach()

Прежде всего, давайте создадимInteger List, а затем используем обычную логику if / else в методеInteger streamforEach():

List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ints.stream() .forEach(i -> < if (i.intValue() % 2 == 0) < Assert.assertTrue(i.intValue() % 2 == 0); >else < Assert.assertTrue(i.intValue() % 2 != 0); >>);

Our forEach method contains if-else logic which verifies whether the Integer is an odd or even number с использованием оператора модуля Java.

3. if/else Логика сfilter()

Во-вторых, давайте посмотрим на более элегантную реализацию с использованием методаStream filter():

Stream evenIntegers = ints.stream() .filter(i -> i.intValue() % 2 == 0); Stream oddIntegers = ints.stream() .filter(i -> i.intValue() % 2 != 0); evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 == 0)); oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() % 2 != 0));

Выше мы реализовали логику if / else, используя методStream filter()to separate the Integer List into two Streams, one for even integers and another for odd integers.

Читайте также:  Write response in php

4. Заключение

В этой быстрой статье мы изучили, как создать Java 8Stream и как реализовать логику if / else с помощью методаforEach().

Кроме того, мы узнали, как использовать методStream filter для достижения аналогичного результата более элегантным способом.

Наконец, доступен полный исходный код, используемый в этом руководствеover on Github.

Источник

Using ‘if-else’ Conditions with Java Streams

Learn to use the if-else conditions logic using Java Stream API to filter the items from a collection based on certain conditions.

1. The ‘ if-else ‘ Condition as Consumer Implementation

The ‘if-else’ condition can be applied as a lambda expression in forEach() function in form of a Consumer action.

Consumer is a functional interface whose functional method is ‘ void accept(Object) ‘. It represents an operation that accepts a single input argument and returns no result.

In the given example, we are checking if a number is even then print a message, else print another message for an odd number.

ArrayList numberList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); Consumer action = i -> < if (i % 2 == 0) < System.out.println("Even number :: " + i); //Or any other user action we want to do >else < System.out.println("Odd number :: " + i); //Or any other user action we want to do >>; numberList.stream() .forEach(action);
  • We can perform any kind of operation on the stream items instead of just printing the items to the console, e.g. storing the items to two separate lists or passing the items to other method calls.
  • We can write as many if-else statements as required.
  • We can also write the pass the Consumer implementation as an inline lambda expression to the forEach() function.
Arrays.asList(-1, 1, -2, 3, 4, -5, 6, 0).stream() .forEach( i -> < if (i == 0) < System.out.println("Number is 0"); >else if (i > 0) < System.out.println("Positive Number"); >else < System.out.println("Negative Number"); >> ); 

2. The ‘ if’ Condition with Predicates

If we intend to apply only ‘if’ logic then we can pass the condition directly do the filter() function as a Predicate.

In the given example, we are checking if a number is an even number then printing a message.

ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); Predicate isEven = i -> i % 2 == 0; numberList.stream() .filter(isEven) .forEach(System.out::println);

Using one of the above given two methods, we can apply any combination of if-else conditions in Java 8 stream elements.

Источник

Java 8 Streams if else logic

Twitter Facebook Google Pinterest

A quick guide to if-else conditions in java 8 with streams.

1. Overview

If you are new to the java 8 stream, It is recommended to read the in-depth on the basics of java 8 streams.

2. Java Conventional If Else condition

In the below example, a List with the integers values is created. Next, we run the for loop from index 0 to list size — 1. Take each index value and check the number is even or not using if-else condition.

package com.javaprogramto.java8.streams.filter.ifelse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class IfElseExample < public static void main(String[] args) < ListnumbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100); List evenList = new ArrayList<>(); List oddList = new ArrayList<>(); for (int index = 0; index < numbersList.size(); index++) < if (numbersList.get(index) % 2 == 0) < evenList.add(numbersList.get(index)); >else < oddList.add(numbersList.get(index)); >> System.out.println("Even numbers list - " + evenList); System.out.println("Odd numbers list - " + oddList); > >
Even numbers list - [10, 20, 24, 16, 100] Odd numbers list - [13, 15, 17]

3. Java 8 Streams If Else condition In forEach()

In java 8, stream api is added with the forEach() method and inside this, we can add the if-else conditions.

package com.javaprogramto.java8.streams.filter.ifelse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Java8StreamForEachExample < public static void main(String[] args) < ListnumbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100); List evenList = new ArrayList<>(); List oddList = new ArrayList<>(); numbersList.stream().forEach(number -> < if (number % 2 == 0) < evenList.add(number); >else < oddList.add(number); >>); System.out.println("Even numbers list - " + evenList); System.out.println("Odd numbers list - " + oddList); > >
Even numbers list - [10, 20, 24, 16, 100] Odd numbers list - [13, 15, 17]

4. Java 8 Streams If Else condition

By using traditional for loop and if-else conditions, we could get the odd and even numbers into separate lists but we had to write many lines of code.

But, with the new concepts of java 8 streams, the full logic can be reduced to two lines to get the separate even and odd numbers lists.

Use the java 8 stream filter() method to get the equivalent functionality of the traditional if condition.

The Predicate is the functional interface that does the job of if condition. But this predicate statement should be passed to the filter() method so that the predicate function is evaluated.

package com.javaprogramto.java8.streams.filter.ifelse; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8StreamIfElseExample < public static void main(String[] args) < ListnumbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100); List evenList = numbersList.stream().filter(number -> number % 2 == 0).collect(Collectors.toList()); List oddList = numbersList.stream().filter(number -> number % 2 == 1).collect(Collectors.toList()); System.out.println("Even numbers list - " + evenList); System.out.println("Odd numbers list - " + oddList); > >
Even numbers list - [10, 20, 24, 16, 100] Odd numbers list - [13, 15, 17]

4. Java 8 Streams Multiple If conditions

Actually, we can call the filter() multiple times on the streams. So, if you have multiple conditions in your use case, either you can add all conditions in the single predicate statement or you can make calls to the filter() method as many times you want.

Here, we have two conditions — first one is number is greater than 20 and second is checking the even number.

package com.javaprogramto.java8.streams.filter.ifelse; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8StreammultipleIfExample < public static void main(String[] args) < ListnumbersList = Arrays.asList(10, 13, 15, 20, 24, 16, 17, 100); List evenList = numbersList.stream() .filter(number -> number > 20) .filter(number -> number % 2 == 0) .collect(Collectors.toList()); System.out.println("Even numbers list - " + evenList); > >
Even numbers list - [24, 100]

6. Conclusion

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content

Источник

Оцените статью