EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 reduce
Secondary Sidebar
Phishing and Pharming

Shell Scripting Interview Questions

Software Testing Interview Questions

What is JavaScript?

WordPress vs Wix

Web Services Interview Questions

Java 8 reduce

Introduction to Java 8 reduce

Java 8 reduce is a terminal operation that aggregates the stream into primitive types of types. Java 8 provides stream API, which contains a set of predefined reduction operations like sum, average, min, max, and count. The operations returns the value by combining the stream of elements. In Java, we use the reduce method as a stream interface, which we define in the stream API.

Java 8 reduce

Key Takeaways

  • It is a method for combining all of the elements that we used in our code. The reduce method applies the binary operation to each element.
  • The reduce method in Java 8 allows for a single result from a specified sequence of elements when used on a regular basis.

What is Java 8 reduce?

It is used to combine all the elements. The reduce method is used for applying the binary operator to every element we present in the stream. In the specified stream, the first argument operator returns the value of the previous application, and the second returns the element of the current stream. Java 8 reduce method produces a single result for a sequence of elements by repeatedly applying the combining operation from the sequence of the elements called reducing.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In Java, we must perform the operation where the stream reduces its value to single resultant multiple times. Reduce in Java 8 is a repeated process that was used to combine all of the elements. It is also a terminal operation that aggregates the stream data type.

Java 8 Stream Reduce Methods

The java stream reduce methods produces the final value from the stream values. We are using the stream reduce method in java 8 with sequential and parallel streams with the three variants as follows:

  • By using a single parameter called accumulator.
  • By using two parameter identity and using accumulator.
  • By using three parameters, combiner and accumulator.

The below syntax shows java 8 stream reduce methods as follows.

In the below syntax, we are using type as a T.

Syntax:

T reduce (reduce method) (T identity, operator <T (Function)>, accumulator);

Where,

  • Reduce: It is a stream function.
  • Identity: It is the initial value.
  • T and accumulator: It is a function that was used to combine two values.

The below example shows that java 8 stream reduction methods are as follows:

Example #1

We are using reduce method on string values.

Code:

import java.util.*;
class stud {
public static void main(String[] args)
{
List<String> words = Arrays.asList("ABC", "PQR", "XYZ",
"MNP", "BCD");
Optional<String> longestString = words.stream ()
.reduce((word2, word3)
-> word2.length() > word3.length()
? word2 : word3);
longestString.ifPresent (System.out::println);
}
}

Output:

Java 8 reduce Method

Example #2

We are using combined string.

Code:

import java.util.*;
class Stud {
public static void main(String[] args)
{
String[] array = { "ABC", "ABC", "PQR" };
Optional<String> String_combine = Arrays.stream (array)
.reduce((str2, str3)
-> str2 + "-" + str3);
if (String_combine.isPresent()) {
System.out.println (String_combine.get ());
}
}
}

Output:

Java 8 reduce 8

Java 8 Stream Collect Methods

The stream collect methods in java 8 allows the accumulated result into the container’s choice. The collect method is defined into the stream class, so we are defining the stream class which we are calling into the stream after doing filtering or mapping. It is accepting the collector for accumulating stream elements into the specified collection. The collector class provides different types of methods.

The collector interface is providing a wrapper for the accumulator, supplier, and combiner for specified objects.

There are three parameters of collect methods in the java 8 stream as follows:

  • Supplier: This is a function that creates new mutable results for the specified container. For the execution, which was parallel, it will create the function multiple times and returns a fresh value every time.
  • Accumulator: It’s stateless function that folds the element into the result container.
  • Combiner: It is a stateless function that accepts parallel result containers and merges the same.

The below example shows stream collect methods as follows:

Example #1

In the below example, we are using string as follows.

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class stud {
public static void main(String[] args){
List<String> listOfString = Arrays.asList("ABC", "ACD", "XYZ");
System.out.println("input String: " + listOfString);
List<String> Astring = listOfString.stream()
.filter(s -> s.startsWith ("A"))
.collect(Collectors.toList());
System.out.println ("\nString starts with A: "
+ Astring);
}
}

Output:

Java 8 reduce String

Example #2

In the below example, we are using a set method with stream collect methods as follows.

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class stud {
public static void main(String[] args){
List<String> str = Arrays.asList ("ABC", "CBD", "XYZ");
System.out.println ("input String: " + str);
Set<String> startC   = str.stream()
.filter(s -> s.startsWith("C"))
.collect (Collectors.toSet());
System.out.println ("letter starts with C: "  + startC);
}
}

Output:

using set method

Signature Methods

Signature methods in java are defined structure methods that were designed by the coder. Signature method is nothing but the combination of a parameter list and the name of the methods. A single class in java does not contain the two methods using the same signature. If we are declaring two methods by using the same signature, then it will throw the compilation error. This method does not include the method return type.

Below example shows signature methods as follows:

Example #1

In the below example, printName method does not contain the return type.

Code:

class stud {
String stud_name = "ABC";
void printName () {
System.out.println (stud_name);
}
public static void main(String[] args){
stud st = new stud();
st.printName ();
}
}

Output:

contains the return type

Example #2

In the below example, printName method does not contain the return type, but it will contain the string type.

Code:

class stud {
String stud_nm = "ABC";
void printName(String stud_nm) {
System.out.println(stud_nm);
}
public static void main(String[] args)
{
stud st = new stud();
st.printName("ABC");
}
}

Output:

Java 8 reduce - String type

Examples of Java 8 reduce

Given below are the examples mentioned:

Example #1

In the below example, we are using reduce method to get sum of all elements as follows.

Code:

import java.util.*;
class stud {
public static void main(String[] args)
{
List<Integer> array = Arrays.asList(-12, 20, 14, 16, 28);
int sum = array.stream ().reduce(0, (ele1, ele2) -> ele1 + ele2);
System.out.println("sum is " + sum);
}
}

Output:

Sum of all elements

Example #2

In the below example, we are taking all the stud details.

Code:

import java.util.*;
import java.util.stream.IntStream;
class stud {
public static void main(String[] args)
{
int mul = IntStream.range (2, 8)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1);
System.out.println ("Mul is : " + mul);
}
}

Output:

Java 8 reduce - Stud

FAQs

Given below are the FAQs mentioned:

Q1. What is the use of java 8 reduce method?

Answer: It is a terminal operation that aggregates a stream into primitive types. It provides the stream API, which includes the operation of predefined reductions.

Q2. What is the use of T accumulator in java 8 reduce method?

Answer: The T accumulator performs reduction on stream elements, by using identity value and function of associate accumulation, it will return the reduced value.

Q3. What is the use of combiner in java 8 reduce method?

Answer: The combiner is used to combine the result which was partial for the specified reduction operation.

Conclusion

To combine all the elements, the java 8 reduce method is used. The reduce method is used for applying the binary operator to every element we present in the stream. Reduce operations in Java 8 return a value by combining a stream of elements. In Java, we use the reduce method as a stream interface, which is defined in the stream API.

Recommended Articles

This is a guide to Java 8 reduce. Here we discuss the introduction, java 8 stream reduce methods, signature methods, and examples. You may also have a look at the following articles to learn more –

  1. Text File in Java
  2. Java 8 forEach
  3. Java for Automation Testing
  4. Java SFTP
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more