Showing posts with label Java Stream API. Show all posts
Showing posts with label Java Stream API. Show all posts

Sunday, November 3, 2024

Java Stream - min() With Examples

In Java Stream API there is a min() method that is used to get the minimum element of this stream according to the provided Comparator. In this post we’ll see some examples of the min() method.

Syntax of the Stream.min() method

min is a terminal operation and its syntax is as given below-

Optional<T> min(Comparator<? super T> comparator)

Here comparator argument is an implementation of the Comparator to compare elements of this stream.

Method returns an Optional describing the minimum element of this stream, or an empty Optional if the stream is empty.

Stream.min is considered a special case of a reduction operation as it takes a sequence of input elements and combines them into a single summary result.

min() method Java examples

1. Finding min value from a stream of numbers.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(Integer::compare);
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

Output

Minimum element: 1

2. In the following example custom comparator is passed as an argument to the min() method to get minimum method as per the passed Comparator.

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(new MyComparator());
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer o1, Integer o2) {
    return o1.compareTo(o2);
  }
}

Output

Minimum element: 1

3. Using Stream.min() method with custom object. In the example, objects of Employee class are used and the objective is to find minimum salary using the min() method of the Java Stream API.

Employee class used is as given here.

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
}

In the example mapToInt() method is used to get the salary part of the employee object which is then passed to the min() to get the minimum salary.

public class StreamMin {
  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 24, "Mark", 'M', 9000), 
                new Employee("E004", 37, "Rani", 'F', 10000),
                new Employee("E005", 32, "Anuj", 'M', 12000));  
     OptionalInt minEmpSal = empList.stream()
                .mapToInt(Employee::getSalary)
                .min();
      if(minEmpSal.isPresent()){
        System.out.println("Minimum salary: " + minEmpSal.getAsInt());
      }
  }
}

Output

Minimum salary: 5000

That's all for this topic Java Stream - min() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - max() With Examples
  2. Java Stream - filter() With Examples
  3. Java Stream - distinct() With Examples
  4. Java Stream - findFirst() With Examples
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. How to Sort ArrayList of Custom Objects in Java
  2. equals() And hashCode() Methods in Java
  3. Type Casting in Java With Conversion Examples
  4. StringJoiner Class in Java With Examples
  5. Writing a File Asynchronously Java Program
  6. Spring Integration With Quartz Scheduler
  7. Operator Overloading in Python
  8. Angular Access Control CanActivate Route Guard Example

Wednesday, April 3, 2024

Java Stream API Tutorial

If we have to point out the most important inclusion in Java 8 apart from lambda expressions then that has to be Stream API in Java. Stream API usually works in conjunction with lambda expression and provide an easy yet efficient way to perform data manipulation operations like sort, filter, map, reduce etc.

This Javs Stream API tutorial gives an overview of what exactly is a stream in Stream API and what all types of Stream operations are there.


What is Stream in Java Stream API

A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

Stream API in Java
Stream data flow

Monday, March 25, 2024

Java Stream API Examples

In the post Java Stream API Tutorial we have already got an introduction of Stream API. A Stream can be defined as a sequence of elements supporting sequential and parallel aggregate operations. Using these aggregation operations we can create a pipeline. Some of the aggregation operations provided are collect, concat, count, distinct, filter, forEach, limit, map, max, min, reduce, sorted. In this post we’ll see some Java stream API examples using these operations and also create pipeline consisting sequence of aggregate operations.


Java Stream API count() method example

count method returns the count of elements in the given stream.

Note that this is a special case of a reduction and it is a terminal operation.

List<Integer> myList = Arrays.asList(7, 18, 10, 24, 17, 5);  
long count = myList.stream().count();
System.out.println("Total elements in the list " + count);

This code snippet will give the count of the elements in the List.

Now if you want to get the count of the elements greater than 10 you can create a pipeline where you first filter on the predicate that you want those elements of the list whose value is greater than 10 and then count those elements.

List<Integer> myList = Arrays.asList(7, 18, 10, 24, 17, 5); 
long count = myList.stream().filter(i -> i > 10).count();
System.out.println("Total elements in the list with value greater than 10 " + count);

Java Stream API concat() method example

concat() method in Java Stream creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

List<String> myList = Arrays.asList("1", "2", "3", "4", "5");
  
String[] arr1 = { "a", "b", "c", "d" };
// concatenating two streams
Stream<String> stream = Stream.concat(myList.stream(), Arrays.stream(arr1));
stream.forEach(System.out::print);

Output

12345abcd

Here you can see the concatenated stream is returned. If you are wondering what is this System.out::print refer Method reference in Java 8. You may also want to read about forEach statement in Java 8.

Since parameters of the concat operations are streams so all the aggregation operations can be applied to them too. As example if there are two lists having name and you want a merged list with all the names that start with “A” that can be done as follows–

List<String> nameList1 = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");
  
List<String> nameList2 = Arrays.asList("Anthony", "Samir", "Akash", "Uttam");
  
String[] arr1 = { "a", "b", "c", "d" };
// concatenating two streams
Stream<String> stream = Stream.concat(nameList1.stream().filter(n -> n.startsWith("A")), nameList2.stream().filter(n -> n.startsWith("A")));

stream.forEach(System.out::println);

Java Stream API distinct() method example

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

Using distinct method of the Java Stream API, duplicate elements from a collection like list can be removed very easily by creating a pipeline where distinct method will return a stream having distinct elements only which can later be collected in a list using collect method.

List<Integer> myList = Arrays.asList(7, 18, 10, 7, 10, 24, 17, 5);
  
System.out.println("Original list: " + myList);
List<Integer> newList = myList.stream().distinct().collect(Collectors.toList());

System.out.println("new List : " + newList);

Java Stream API filter() method example

filter method returns a stream consisting of the elements of this stream that match the given predicate.

Here note that Predicate is a functional interface and can be implemented as a lambda expression. In the above examples we have already used filter method.

As an example let’s say we have a list of names and we want to print names which doesn’t start with “A”.

List<String> nameList = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");
  
nameList.stream().filter(n -> !n.startsWith("A")).collect(Collectors.toList()).forEach(System.out::println);

Output

Ram
Manish
Rajat

Java Stream API limit() method example

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

If you want 10 random numbers, then you can use limit method with the int stream.

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

Java Stream API map() method example

Returns a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream. Note that this is an intermediate operation.

As Example– If you have a list of salaries and you want to increase it by 10%.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
  
myList.stream().map(i -> (i+ i * 10/100)).forEach(System.out::println);

findFirst() and findAny() methods in Java Stream API

  • findFirst()- Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order (List or Array wil be ordered, where as set or map won’t), then any element may be returned.
  • findAny()- Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
List<String> nameList = Stream.of("amy", "nick", "margo", "desi");
Optional<String> name = nameList.stream().findFirst();
System.out.println("First Name " + name);

name = nameList.parallelStream().findAny();
System.out.println("First Name " + name);

Output

First Name Optional[amy]
First Name Optional[margo]

You can see in case of findFirst() method, first element of the list is displayed. Even with parallelStream, findFirst() will give the first element.

Whereas in case of findAny() method any random element is picked. You can see that findAny() method is used with parallelStream here.

max and min methods in Java Stream API

  • max- Returns the maximum element of this stream according to the provided Comparator.
  • min- Returns the minimum element of this stream according to the provided Comparator.

max and min are also reduction operations. Both of them are terminal operations.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
// Obtain a Stream to the array list.
Stream<Integer> myStream = myList.stream();
Optional<Integer> val = myStream.min(Integer::compare);
if(val.isPresent()){
 System.out.println("minimum value in the list " + val.get());
}  
Optional<Integer> val1 = myList.stream().max(Integer::compare);
if(val1.isPresent()){
 System.out.println("maximum value in the list " + val1.get());
}

Note that here Optional class is used. To know more about Optional class refer Optional class in Java 8.

Java Stream API sorted() method example

sorted method returns a stream consisting of the elements of this stream, sorted according to natural order or there is another variant where custom comparator can be provided.

List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);
myList.stream().sorted().forEach(System.out::println);

Summary Statistics classes

A state object for collecting statistics such as count, min, max, sum, and average. There are different SummaryStatistics classes in Java Stream API like IntSummaryStatistics, DoubleSummaryStatistics, LongSummaryStatistics.

As example–

 
List<Integer> myList = Arrays.asList(7, 5, 4, 24, 17, 6);
IntSummaryStatistics stats = myList.stream().collect(Collectors.summarizingInt(i-> i));

System.out.println("Sum - " + stats.getSum());
System.out.println("Count " + stats.getCount());
System.out.println("Average " + stats.getAverage());
System.out.println("Max " + stats.getMax());
System.out.println("Min " + stats.getMin());

Here Collectors.summarizingInt method is used which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

In place of

IntSummaryStatistics stats = myList.stream().collect(Collectors.summarizingInt(i-> i));

Using mapToInt method it can also be written as -

IntSummaryStatistics stats = myList.stream().mapToInt(i -> i).summaryStatistics();

That's all for this topic Java Stream API Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Parallel Stream in Java Stream API
  2. Primitive Type Streams in Java Stream API
  3. Reduction Operations in Java Stream API
  4. Lambda Expressions in Java 8
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. How HashMap Works Internally in Java
  2. How ArrayList Works Internally in Java
  3. Java ReentrantLock With Examples
  4. Difference Between ArrayList And CopyOnWriteArrayList in Java
  5. Lock Striping in Java Concurrency
  6. Java ThreadLocal Class With Examples
  7. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  8. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring

Thursday, March 21, 2024

Java Stream - count() With Examples

In this tutorial you’ll learn about the count() method in the Java Stream API with the help of few examples.

count() method in Java

count() method returns the count of elements in the stream.

Syntax of count() method-

long count()

Some important points about count() method-

  1. It is a special case of a reduction operation which means it takes a sequence of input elements and reduce them into a single summary result.
  2. It is a terminal operation which means after count() operation the stream pipeline is considered consumed, and can no longer be used.

count() method Java examples

1. In the first example count() is used to get the count of elements in a List where List is used as a stream source.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 6

2. Since count is a terminal operation so stream is considered closed after count operation but before count, intermediate operations like filter can be used to filter out certain elements and then get the count of the resulting stream. For example if we want count of positive elements in a list.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().filter(n -> n > 0).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 4

3. In the following example count is used to get the count of employees having salary greater than 10000.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class StreamCountDemo {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 40, "Remington", 'M', 5000), 
                new Employee("E004", 37, "Bianca", 'F', 11000),
                new Employee("E005", 35, "Dominic", 'M', 7000), 
                new Employee("E006", 28, "Amanda", 'F', 14000));
    long elementCount = empList.stream().filter(e -> e.getSalary() > 10000).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 2

That's all for this topic Java Stream - count() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - boxed() With Examples
  2. Java Stream - sorted() With Examples
  3. Java Stream - distinct() With Examples
  4. Parallel Stream in Java Stream API
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Type Erasure in Java Generics
  2. SerialVersionUID And Versioning in Java Serialization
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. Difference Between StackOverflowError and OutOfMemoryError in Java
  5. Docker Tutorial: Introduction to Docker
  6. Benefits, Disadvantages And Limitations of Autowiring in Spring
  7. Spring MVC JSON as Response Example
  8. Angular Access Control CanActivate Route Guard Example

Wednesday, March 20, 2024

Java Stream - filter() With Examples

In this tutorial you will see some examples of filter() method in Java Stream API. filter() method is used to filter out some elements based on the passed condition and the remaining elements, that satisfy the condition, are returned as a new Stream.


filter() in Java

filter() in Java stream is an intermediate operation and its syntax is as given below-

Stream<T> filter(Predicate<? super T> predicate)

Here Predicate, which is a functional interface, is used to pass the condition that is used to filter out elements. Since Predicate is a functional interface so it is usually implemented as a lambda expression.

Wednesday, March 6, 2024

Java Stream - distinct() With Examples

In this tutorial you will see some examples of distinct() method in Java Stream API. Stream.distinct() method is used to remove duplicate elements and the method returns a new stream consisting of the distinct elements. To determine which elements are duplicates distinct() method uses the equals() method of the Object class.

distinct() in Java Stream

Syntax of the distinct() method is as given below-

Stream<T> distinct()

Here are some important points about the distinct operation.

  1. It is a stateful intermediate operation which means it may incorporate state from previously seen elements when processing new elements.
  2. Method takes no arguments and returns a new Stream consisting of the distinct elements.
  3. For ordered streams, distinct operation is stable i.e. if there are duplicate elements the element appearing first in the encounter order is preserved.
  4. For unordered streams there are no stability guarantees.

Tuesday, March 5, 2024

Java Stream - limit() With Examples

In Java Stream API limit(long maxSize) method is used to truncate the stream so that it is not longer than maxSize in length and the method returns a stream consisting of that many elements of this stream.

Java Stream limit() method

Syntax of the limit method is as given below-

Stream<T> limit(long maxSize)

Here maxSize argument represents the number of elements the stream should be limited to.

If maxSize is negative then IllegalArgumentException is thrown otherwise a new Stream is returned which is no longer than maxSize in length.

Notes about limit() method

  • limit() is generally considered a cheap operation on sequential stream pipelines
  • limit() can be quite expensive on ordered parallel pipelines, since limit(n) is constrained to return not just any n elements, but the first n elements in the encounter order.
  • It is a short-circuiting stateful intermediate operation. Since limit() method returns a new stream that makes it a stateful intermediate operation. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result.

limit() Java examples

1. Getting a sublist from a List by limiting the number of elements to the first n elements of the original list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamLimit {
  public static void main(String[] args) {
    StreamLimit sl = new StreamLimit();
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> subList = numList.stream().limit(5).collect(Collectors.toList());     
    System.out.println("Sublist after limiting elements- " + subList);
  }
}

Output

Sublist after limiting elements- [1, 2, 3, 4, 5]

2. Getting 10 random numbers by using limit() with generate() method.

public class StreamLimit {
  public static void main(String[] args) {
    Stream.generate(Math::random)
          .map(n -> (int)(n * 100))
          .limit(10)
          .forEach(System.out::println);
  }
}

That's all for this topic Java Stream - limit() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - skip() With Examples
  2. Java Stream - distinct() With Examples
  3. Java Stream - max() With Examples
  4. Primitive Type Streams in Java Stream API
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Just In Time Compiler (JIT) in Java
  2. Byte Streams in Java IO
  3. How to Get The Inserted ID (Generated ID) in JDBC
  4. Method Reference in Java
  5. java.lang.ClassCastException - Resolving ClassCastException in Java
  6. Creating PDF in Java Using Apache PDFBox
  7. Method Overloading in Python
  8. Spring Boot Spring Initializr

Thursday, January 11, 2024

Java Stream API Interview Questions And Answers

In this post Java Stream API Interview Questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Stream API in Java?

    Stream API is added in Java 8 and works very well in conjunction with lambda expressions. You can create a pipeline of stream operations to manipulate data by performing operations like search, filter, sort, count, map etc.

    Read more about Stream API in Java here.

  2. What is stream in Stream API?

    A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc.), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

    Read more about Stream API in Java here.

  3. Explain stream operations with an example?

    In this example let's take an ArrayList as an input. There are two operations; take only those elements of the list which are greater than 5 and then sort the result. After that print the elements of the list.

    // Creating the list
    List<Integer> numList = Arrays.asList(34, 6, 3, 12, 65, 1, 8);
    numList.stream().filter((n) -> n > 5).sorted().forEach(System.out::println); 
    
    Here ArrayList is the data source for the stream and there are two intermediate operations–
    • filter- Filter condition here is; take only those elements of the list which are greater than 5. Click to read more about filter() method.
    • sorted- sort that filtered output of the last stream. Click to read more about sorted() method.
    Terminal operation here is forEach statement (provided in Java 8) which iterates the sorted result and displays them. Read more about forEach statement in Java 8 here.

  4. How many types of Stream operations are there?

    Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines.

    • Intermediate operations return a new stream. They are always lazy; executing an intermediate operation 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.
    • Terminal operations such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
    See some Stream API examples here.

  5. What are Stateless and Stateful operations in Java stream?

    Intermediate operations are further divided into stateless and stateful operations.

    • Stateless operations, such as filter() and map(), retain no state from previously seen element when processing a new element, each element can be processed independently of operations on other elements.
    • Stateful operations, such as distinct() and sorted(), may incorporate state from previously seen elements when processing new elements. Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
    See some Stream API examples here.

  6. What is Parallel Stream in Java Stream API?

    You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub-streams.

    As example- Collection has methods Collection.stream() and Collection.parallelStream(), which produce sequential and parallel streams respectively.

    Read more about parallel stream here.

  7. What is the benefit of using parallel stream?

    When parallel stream is used the Java runtime partitions the stream into multiple sub-streams. This parallel execution of data, with each sub-stream running in a separate thread, will result in increase in performance.

    Read more about parallel stream here.

  8. Can you use streams with primitives?

    Streams work only on object references. They can’t work on primitive types so you have two options to use primitives.

    • You can wrap primitive types into a wrapper object. As example Stream<Integer>, Stream<Long> or Stream<Double>.
    • Second and better option is to use primitive specializations of Stream like IntStream, LongStream, and DoubleStream that can store primitive values.
    • As example- IntStream is = IntStream.of(3, 4, 5, 6);

    Read more about Primitive type streams in Java here.

  9. How can you transform Stream to primitive type Stream?

    Stream interface provides methods mapToInt, mapToDouble and mapToLong that can be used to transform stream of objects to a stream of primitive types.

    As example- If you have a list of employee objects and you want to get the maximum salary. In that case you can take the salary field and use mapToInt method to get a stream of primitive types. Then you can use max method on that primmitive type stream.

    OptionalInt maxSalary = empList.parallelStream().mapToInt(e -> e.getSalary()).max();
    
    Read more about Primitive type streams in Java Stream API here.

  10. What are Reduction Operations in Java Stream API?

    Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations because these operations reduce the stream to a single non-stream value.

    Read more about Reduction Operations in Java Stream API here.

  11. What are Map operation in Java Stream API?

    Map operations are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

    Since new stream is returned map operation is an intermediate operation.

    Read more about Map operation in Java Stream API here.

  12. What is a mutable reduction operation?

    A mutable reduction operation can be defined as an operation that accumulates input elements into a mutable result container, such as a Collection or StringBuilder.

    Read more about Reduction operation in Java Stream API here.

  13. What is a collect method in Java stream?

    Using collect method you can store the result of the stream operation into a collection. This is a terminal operation.

    As example- If you have employee objects and you want a list having names of all the employees you can use the toList method of the Collectors class.

    List<String> nameList = empList.stream().map(Employee::getName).collect(Collectors.toList());
    
    Read more about Collecting in Java Stream API here.

  14. What is flatMap() method in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this-

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    

    flatMap() method means you are bringing both of them together, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

    Read more about FlatMap in Java here.

  15. What is a Spliterator in Java?

    Spliterators, like iterators, are for traversing the elements of a source. Spliterator can split the source and iterate the splitted parts in parallel. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.

    You can also use spliterator even if you are not using parallel execution.

    Read more about Spliterator in Java here.

Related Topics

  1. Java Lambda Expressions Interview Questions And Answers
  2. Java Concurrency Interview Questions And Answers
  3. Java Multithreading Interview Questions And Answers
  4. Java Collections Interview Questions And Answers
  5. Java Exception Handling Interview Questions And Answers
  6. Java String Interview Questions And Answers
  7. Java OOP Interview Questions And Answers
  8. Core Java Basics Interview Questions And Answers

Wednesday, March 1, 2023

Map Operation in Java Stream API

Map operations in Java Stream API, as the name suggests, are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

One thing to note here is; since new stream is returned map operation is an intermediate operation.

map method in Java Stream

Java stream API provides the following map method.

<R> Stream<R> map(Function<? super T,? extends R> mapper)- Returns a stream consisting of the results of applying the given function to the elements of this stream.

Here R is the element type of the new stream, T denotes the element type of the existing stream and mapper is the function which will be applied to all the elements of the stream.

Here note that mapper is an instance of Function which is a functional interface. Since it is a functional interface therefore it can be used as the assignment target for a lambda expression or method reference.

map() method examples in Java Stream

  1. You have a stream of some names and you want to get a list where names are stored in upper case. In that case using map() method you can apply a function to all the elements of the stream to convert those elements to upper case and then using collector, collect them in a list.
    public class MappingDemo {
      public static void main(String[] args) {
        List<String> nameList = Stream.of("amy", "nick", "margo", "desi")
                                            .map(s->s.toUpperCase())
                                            .collect(Collectors.toList());
        System.out.println("Names in upper case" + nameList);
    
      }
    }
    

    Output

    Names in upper case[AMY, NICK, MARGO, DESI]
    
  2. You have a list of salaries and you want to increase salaries by 10%.
    List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000);  
    myList.stream().map(i -> (i+ (i * 10/100))).forEach(System.out::println);
    

    Output

    7700
    5500
    4400
    26400
    18700
    6600
    
  3. There is an employee class and you want the name of all the female employees. In this example you can use filter() method to filter female employees and then using map() method you can get the name of those employees. Here using map() method you are transforming employee object to String object.
    public class MappingDemo {
    
      public static void main(String[] args) {
        MappingDemo md = new MappingDemo();
        List<Employee> empList = md.createList();
        System.out.println("--- Name of female employees ---");
        empList.stream()
               .filter(e -> (e.getSex() == 'F'))
               .map(e -> e.getName())
               .forEach(System.out::println);
    
      }
        
      // Stub method to create list of employee objects
      private List<Employee> createList(){
        List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                                       new Employee("E002", 35, "Sheila", 'F', 7000), 
                                       new Employee("E003", 24, "Mukesh", 'M', 9000), 
                                       new Employee("E004", 37, "Rani", 'F', 10000));
        
        return empList;
      }
      
      class Employee {
        private String empId;
        private int age;
        private String name;
        private char sex;
        private int salary;
        Employee(String empId, int age, String name, char sex, int salary){
          this.empId = empId;
          this.age = age;
          this.name = name;
          this.sex = sex;
          this.salary = salary;
        }
        public String getEmpId() {
          return empId;
        }
        public void setEmpId(String empId) {
          this.empId = empId;
        }
        public int getAge() {
          return age;
        }
        public void setAge(int age) {
          this.age = age;
        }
        public String getName() {
          return name;
        }
        public void setName(String name) {
          this.name = name;
        }
        public char getSex() {
          return sex;
        }
        public void setSex(char sex) {
          this.sex = sex;
        }
        public int getSalary() {
          return salary;
        }
        public void setSalary(int salary) {
          this.salary = salary;
        }       
      }
    }
    

    Output

    --- Name of female employees ---
    Sheila
    Rani
    

Variants of map() method

There are three variants of map() method which return a primitive stream.

  • mapToInt(ToIntFunction<? super T> mapper)- Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
  • mapToDouble(ToDoubleFunction<? super T> mapper)- Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
  • mapToLong(ToLongFunction<? super T> mapper)- Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Apart from that, in all the primitive type streams– IntStream, LongStream and Double Stream there is also a mapToObj() method.

For IntStream mapToObj() function is defined like this-

  • mapToObj(IntFunction<? extends U> mapper)- Returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.

map() method with primitive streams examples

  1. If you want to get the total of salaries for the employees (Using the employee class as above), you can use mapToInt() method to get an IntStream consisting of salaries and then apply sum() method on that int stream.
    int totalSalary = empList.stream().mapToInt(e -> e.getSalary()).sum();
    System.out.println("total of salaries " + totalSalary);
    

    Output

    total of salaries 31000
    
  2. If you want to get the maximum salary, you can use mapToInt() method to get an IntStream consisting of salaries and then apply max() method on that int stream to get the maximum salary.
    OptionalInt maxSalary = empList.stream().mapToInt(e -> e.getSalary()).max();
    if(maxSalary.isPresent()){
        System.out.println("Maximum Salary " + maxSalary.getAsInt());
    }
    

    Output

    Maximum Salary 10000
    
  3. For your testing you want to create 500 objects of some class -
    List<Employee> empList = IntStream.rangeClosed(1, 500).mapToObj(Employee::new).collect(Collectors.toList());
    

That's all for this topic Map Operation in Java Stream API. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Tutorial
  2. Parallel Stream in Java Stream API
  3. collect() Method And Collectors Class in Java Stream API
  4. Reduction Operations in Java Stream API
  5. @FunctionalInterface Annotation in Java

You may also like-

  1. New Date And Time API in Java With Examples
  2. Effectively Final in Java 8
  3. How HashMap Works Internally in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Difference Between CountDownLatch And CyclicBarrier in Java
  6. Java ReentrantLock With Examples
  7. Find All Permutations of a Given String Java Program
  8. Spring Component Scan Example

Thursday, January 5, 2023

Reduction Operations in Java Stream API

Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations in Java Stream API because these operations reduce the stream to a single non-stream value.

Examples of these reduction operations can be seen in the post Java Stream API Examples.

Apart from these above mentioned reduction operations, Java Stream API also provides general-purpose reduce methods that can be used with any user supplied logic to get a value from the stream.

Stream API in Java provides three versions of reduce() method-

  1. Optional<T> reduce(BinaryOperator<T> accumulator)- This reduce method returns an object of type Optional which contains the result. Notice that the result stored by Optional is of type T which also happens to be the element type of the stream.

    BinaryOperator is a functional interface which means it will have a single Abstract Method. Thus, accumulator is a function that will implement the method of the interface.
    If you see the description for BinaryOperator it says- Represents an operation upon two operands of the same type, producing a result of the same type as the operands.

    BinaryOperator extends another functional interface BiFunction which has this method-

    • R apply(T t, U u)- Applies this function to the given arguments.
    • Where R is the type of the result, T is the type of the first argument and U is the type of the second argument. (This explanation will help with the third form of the reduce method so please bear with me!).
    But in case of Binary Operator, as we have already seen in the explanation, two operands as well as the result are of same type so apply method effectively becomes T apply(T t, T u) in context of BinaryOperator.

    Here two things to note are-

    • When reduction is performed on the elements of this stream, using accumulation function (which is actually this apply method T apply(T t, Tu)) t will contain the previous result and u will contain the next element.
    • In the first invocation of this form of reduce method t will contain the first element.
  2. T reduce(T identity, BinaryOperator<T> accumulator)- This reduce method returns the result of type T which is same as the element type of the stream. The provided identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t i.e. applying the accumulation operation on the identity value and any element of the stream will give you back the element.

    For example, if the operation is addition then the identity value will be 0 as 0 + element = element, in case operation is multiplication then identity value is 1 as 1 * element = element.

  3. <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)- In the third form you can see there are three parameters where apart from identity and accumulator (which is a BiFunction, as explained above) function there is also a combiner function which is a BinaryOperator. Combiner function gives user a way to tell how partial results are to be combined. It becomes important in case parallel stream is used (we’ll see an example soon).

    Another thing you should have noticed is the return type, here it is different from the element type of the stream. In other two variants of the reduce method return type is either an object of Optional (where value stored in the Optional object is same as element type of the stream) or same as element type of the stream.

Java Stream API reduce method example

Let’s see some examples of the reduce method in Java Streams. For that lets take an Employee class where employee with maximum salary is needed as result. Using the first two variants it can be done as-

Employee class

public class Employee {
    private String lastName;
    private String firstName;
    private String empId;
    private int age;
    private int salary;
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

Class with reduce methods

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class ReduceDemo {

    public static void main(String[] args) {       
        List<Employee> empList = createList();
        
        // Using reduce method which returns Optional object
        Optional<Employee> result = empList.stream().reduce((e1, e2) -> 
          e1.getSalary() > e2.getSalary() ? e1 : e2);
        if(result.isPresent()){
            System.out.println("Employee with max salary - " + result.get().getFirstName() 
             + " salary " + result.get().getSalary());
        }
        
        // Using reduce method with identity element
        Employee emp = empList.stream().reduce(new Employee(), (e1, e2) -> 
          e1.getSalary() > e2.getSalary() ? e1 : e2);
        System.out.println("Employee with max salary - " + emp.getFirstName() 
          + " salary " + emp.getSalary());
        
    }
    
    // /Stub method to create list of employee objects
    private static List createList(){
        List<Employee> empList = new ArrayList<Employee>();
        Employee emp = new Employee();
        emp.setEmpId("E001");
        emp.setAge(40);
        emp.setFirstName("Ram");
        emp.setLastName("Chandra");
        emp.setSalary(5000);
        empList.add(emp);
        emp = new Employee();
        emp.setEmpId("E002");
        emp.setAge(35);
        emp.setFirstName("Sheila");
        emp.setLastName("Baijal");
        emp.setSalary(7000);
        empList.add(emp);
        emp = new Employee();
        emp.setEmpId("E003");
        emp.setAge(24);
        emp.setFirstName("Mukesh");
        emp.setLastName("Rishi");
        emp.setSalary(9000);
        empList.add(emp);    
        return empList;
    }
}

Output

Employee with max salary - Mukesh salary 9000
Employee with max salary - Mukesh salary 9000

Reduce method with combiner example

Here let’s see why combiner is important. If there is a list of numbers and you want to get the product of square root of all the numbers then using reduce method, where no combiner is specified, it can be done as-

public class ReduceDemo1 {
    public static void main(String[] args) {        
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);        
        double productOfSqrRoots = numList.parallelStream().reduce(1.0, (a, b) -> a * Math.sqrt(b));
        System.out.println("" + productOfSqrRoots);                
    }
}

This will give result as 6.344227580643384 which is not correct. It is happening because not specifying a combiner means accumulator function itself will be used as combiner function too. In that case when partial results are combined the square root is done again resulting in wrong value.

Correct way will be to define a combiner function which will just multiply the partial results.

public class ReduceDemo1 {
    public static void main(String[] args) {
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);
        double productOfSqrRoots = numList.parallelStream().reduce(1.0, (a, b) -> 
          a * Math.sqrt(b), (a,b)->a*b);
        System.out.println("" + productOfSqrRoots);        
    }
}

Output

30.0

Here note that this problem will only happen when parallel stream is used if you are using normal stream then there won’t be any partial results to combine.

public class ReduceDemo1 {
    public static void main(String[] args) {        
        List<Double> numList = Arrays.asList(9.0, 4.0, 25.0);        
        double productOfSqrRoots = numList.stream().reduce(1.0, (a, b) -> a * Math.sqrt(b));
        System.out.println("" + productOfSqrRoots);        
    }
}

Since sequential stream is used here rather than parallelStream so you will get a correct output 30.0 now.

Sum using reduce method

Using the Employee class as used above if you want the sum of all the salaries you can do that using reduce method.

int salarySum = empList.stream().reduce(0, (sum, e) -> sum + e.getSalary(), Integer::sum);
System.out.println("Sum of all salaries " + salarySum); 

Though the explicit map-reduce form is more readable and therefore should usually be preferred. Using a chain of map and reduce to do the same thing-

int salarySum1 = empList.stream().mapToInt(Employee::getSalary).reduce(0, (s1, s2) -> s1+s2);
System.out.println("Sum of all salaries " + salarySum1);

This looks more readable, you are first getting the salary of all the employees using the map method and then using reduce method summing them.

That's all for this topic Reduction Operations in Java Stream API. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Tutorial
  2. collect() Method And Collectors Class in Java Stream API
  3. Spliterator in Java
  4. Interface Static Methods in Java
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Effectively Final in Java 8
  2. Covariant Return Type in Java
  3. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  4. Blocking Methods in Java Concurrency
  5. Java ArrayBlockingQueue With Examples
  6. How to Sort an ArrayList in Descending Order in Java
  7. How HashMap Works Internally in Java
  8. Difference Between Checked And Unchecked Exceptions in Java

Friday, April 29, 2022

Spliterator in Java

Spliterator in Java, just like iterator, is used for traversing the elements of a source. The source of elements covered by a Spliterator could be, for example, an array, a Collection, an IO channel, or a generator function.

As the name suggests, Spliterator in Java can split the source and partition off some of its elements as another Spliterator, to be used in possibly-parallel operations. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.


Java Spliterator interface

Spliterator is a generic interface in Java defined as-

Interface Spliterator<T>

Where T is the type of elements returned by this Spliterator.

Java Spliterator methods

Though spliterator will increase performance by traversing the collection in parallel but you can also use spliterator even if you are not using parallel execution.

If you use iterator you have to use two methods hasNext() to ensure that there is next element and then next() method to use that element. Spliterator in Java provides methods that combine these two methods into one and making it more convenient to use. Some of the frequently used methods of Spliterator are-

  • tryAdvance()- If a remaining element exists, performs the given action on it, returning true; else returns false. Its form is-
    tryAdvance(Consumer<? super T> action)
    
    Here action is an instance of Consumer, which is a functional interface, it specifies the function that has to be applied on the next element while traversing the collection (or any other source).
  • forEachRemaining- Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. Its form is-
    default void forEachRemaining(Consumer<? super T> action)
    
  • estimateSize()- Returns an estimate of the number of elements that would be encountered by forEachRemaining traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute. Its form is-
    long estimateSize()
    
  • trySplit()- If current spliterator can be partitioned a new spliterator is created, it partitions the elements of the source so that new spliterator traverse one of the partition while original spliterator traverses the other partition.
  • characteristics()- Returns a set of characteristics of this Spliterator and its elements.

Spliterator characteristics

A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, and SUBSIZED.

These characteristics are defined as constant fields in the Spliterator interface.

Read more about them here: https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html#characteristics--

To see constant values- https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Spliterator

Using characteristics() method will give you a result represented as ORed values of the characterstics relevant for the given source.

Java Spliterator example

If you have a list of names and you want to iterate it and print the names, using iterator it can be done as follows-

public class IteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Iterator<String> itr = nameList.iterator();
    while (itr.hasNext()) {
      System.out.println("name - " + itr.next());   
    }
  }
}

Same iteration of a List can be done using spliterator like this-

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }
}

You can see, with Spliterator, you need to use only one method tryAdvance() which combines both hasNext() and next() methods of the iterator.

Java Spliterator forEachRemaining method example

If you want to convert all the names to lowercase you can use forEachRemaining method.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    splitStr.forEachRemaining((n) -> {
      String x = n.toLowerCase();
      System.out.println("" + x);
    });
  }
}

Java Spliterator trySplit method example

If you want to split the original spliterator so that you can traverse the element in parallel.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    Spliterator<String> splitStr2 = splitStr.trySplit();
    // Check if splitting actually happened, then use it
    if(splitStr2 != null){
      System.out.println("Spliterator-2");
      while(splitStr2.tryAdvance((n) -> System.out.println("name - " + n)));
    }
    // Original spliterator
    System.out.println("Original Spliterator");
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }        
}

Output

Spliterator-2
name - Ram
name - Sheila
name - Mukesh
name - Rani
Original Spliterator
name - Nick
name - Amy
name - Desi
name - Margo

When you are splitting the spliterator, make sure to check that splitting actually happened by checking for null.

Here note one thing, according to Java docs-

If the original thread hands a spliterator off to another thread for processing, it is best if that handoff occurs before any elements are consumed with tryAdvance(), as certain guarantees (such as the accuracy of estimateSize() for SIZED spliterators) are only valid before traversal has begun.

So make sure you first do the splitting then only start any operation on the elements.

Reference- https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Spliterator.html

That's all for this topic Spliterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream API Tutorial
  2. Java Stream API Examples
  3. Primitive Type Streams in Java Stream API
  4. collect() Method And Collectors Class in Java Stream API
  5. Java Stream - Collectors.partitioningBy() With Examples

You may also like-

  1. Method Reference in Java
  2. Interface Static Methods in Java
  3. Deadlock in Java Multi-Threading
  4. Java CyclicBarrier With Examples
  5. CopyOnWriteArrayList in Java With Examples
  6. TreeMap in Java With Examples
  7. Difference Between Comparable and Comparator in Java
  8. Exception Propagation in Java Exception Handling

Friday, April 22, 2022

Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()

Collectors Class in Java Stream API provides many useful utility methods that can be used with Java Streams. One such group of methods, which can be classified as Collectors.averaging methods produces the arithmetic mean of the stream elements. There are following averaging methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)- This method is used to get average of stream of integers. If no elements are present, the result is 0.
  2. public static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)- This method is used to get average of stream of longs. If no elements are present, the result is 0.
  3. public static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get average of stream of doubles. If no elements are present, the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implemented to extract the property to be averaged meaning their implementation produces a int-valued, long-valued and double-valued result respectively.

Collectors.averagingInt() Java example

In this example we’ll get the average of the List elements where elements are of type Integer.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Integer> numbers = Arrays.asList(16, 17, 32, 5, 3);
      double avg = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingLong() Java example

In this example we’ll get the average of the List elements where elements are of type long.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Long> numbers = Arrays.asList(16L, 17L, 32L, 5L, 3L);
      double avg = numbers.stream().collect(Collectors.averagingLong(Long::longValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingDouble() Java example

In this example we’ll get the average of the List elements where elements are of type double.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Double> numbers = Arrays.asList(16.87, 17.34, 23.45, 2.22, 3.67);
      double avg = numbers.stream().collect(Collectors.averagingDouble(Double::doubleValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 12.709999999999999

Collectors.averagingInt with Custom Object Example

In this example we’ll use summing method to get the average of salaries for all the employees.

Employee Class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class CollectorAveraging {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
     double avg = empList.stream().collect(Collectors.averagingInt(Employee::getSalary));
     System.out.println("Average employee salary- " + avg);
  }
}

Output

Average employee salary- 8833.333333333334

That's all for this topic Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble(). If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Collectors.summingInt(), summingLong(), summingDouble()
  2. Java Stream - Collectors.joining() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - noneMatch() With Examples
  5. Java Stream - limit() With Examples

You may also like-

  1. Reflection in Java - Getting Constructor Information
  2. Serialization Proxy Pattern in Java
  3. StringJoiner Class in Java With Examples
  4. Binary Tree Traversal Using Breadth First Search Java Program
  5. Java Collections Interview Questions And Answers
  6. Installing Anaconda Distribution On Windows
  7. Autowiring in Spring Using XML Configuration
  8. Spring Batch Processing With List of Objects in batchUpdate() Method

Thursday, April 21, 2022

Java Stream - Collectors.summingInt(), summingLong(), summingDouble()

Collectors Class in Java Stream API is an implementation of Collector interface and provides many useful operations that can be used with Java Streams. One such group of methods, which can be classified as Collectors.summing methods, is used to add the stream elements. There are following summing methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)- This method is used to get the sum of stream of ints, if there is no element in the stream then the result is 0.
  2. public static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)- This method is used to get the sum of stream of longs, if there is no element in the stream then the result is 0.
  3. public static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get the sum of stream of doubles, if there is no element in the stream then the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implementd to extract the property to be summed meaning their implementation produces a int-valued, long-valued and double-valued result.

Collectors.summingInt() Java example

In this example we’ll get the sum of the List elements where elements are of type Integer.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorSumming {

  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(11, 5, 2, 10, 1);
      int sum = numbers.stream().collect(Collectors.summingInt(Integer::intValue));
      System.out.println("Sum of list elements: " + sum);

  }
}

Output

Sum of list elements: 29

Collectors.summingLong() Java example

In this example we’ll get the sum of the List elements where elements are of type Long.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Long> numbers = Arrays.asList(11L, 5L, 2L, 10L, 1L);
      long sum = numbers.stream().collect(Collectors.summingLong(Long::longValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 29

Collectors.summingDouble() Java example

In this example we’ll get the sum of the List elements where elements are of type Double.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Double> numbers = Arrays.asList(11.5, 5.0, 2.65, 10.34, 7.89);
    double sum = numbers.stream().collect(Collectors.summingDouble(Double::doubleValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 37.38

Collectors.summingInt with Custom Object Example

In this example we’ll use summing method to get the sum of salaries for all the employees.

Employee Class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class CollectorSumming {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
    int sum = empList.stream().collect(Collectors.summingInt(Employee::getSalary));
      System.out.println("Sum of employee salaries: " + sum);
  }
}

Output

Sum of employee salaries: 53000

That's all for this topic Java Stream - Collectors.summingInt(), summingLong(), summingDouble(). If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()
  2. Java Stream - Collectors.teeing() With Examples
  3. Java Stream - Collectors.partitioningBy() With Examples
  4. Spliterator in Java
  5. Java Stream - limit() With Examples

You may also like-

  1. JVM Run-Time Data Areas - Java Memory Allocation
  2. Shallow Copy And Deep Copy in Java Object Cloning
  3. Is String Thread Safe in Java
  4. Java Program to Get Current Date and Time
  5. Angular First App - Hello world Example
  6. Java Application With User Input in Docker Container
  7. Spring MVC Pagination Example Using PagedListHolder
  8. Spring Boot Hello World Web Application Example