Comparing Streams to Loops in Java


Stream is a pipeline system, which is mainly used to aggregate some operations like (filter(), map(), forEach(), and collect()) in a Java environment. This function consists of a source which is followed by the value of zero and then terminate the operation. A function is an input output stream whis mainly depends on the input arguments.

Every stream works when −

  • It starts from a data source.

  • Process the data elements through a pipeline.

  • Terminates itself in a terminal operation.

Here is an example −

Benchmark Is Here Mode Cnt Score Error
Units
ForLoopPerformanceTest.usingForEachLoop thrpt 20 259.008 ± 17.888
ops/s
ForLoopPerformanceTest.usingIterator thrpt 20 256.016 ± 10.342
ops/s
ForLoopPerformanceTest.usingSimpleForLoop thrpt 20 495.308 ± 12.866
ops/s
ForLoopPerformanceTest.usingStream thrpt 20 257.174 ± 15.880
ops/s

Algorithm of Comparing Streams to Loops

In this possible algorithm, we are going to show you how to perform the comparing process between two individual streams to get the value from it.

  • Step 1 − Start the process.

  • Step 2 − Import and declare the Java packages.

  • Step 3 − Declare a public main class.

  • Step 4 − Declare a main driver method.

  • Step 5 − Declare a normal integer stream.

  • Step 6 − Add a new line stream.

  • Step 7 − Mention an integer stream with a skip value.

  • Step 8 − Add a new inline value.

  • Step 9 − Add more strings how much you need.

  • Step 10 − Declare a string.

  • Step 11 − Write an output stream.

  • Step 12 − Sort the array and print them.

  • Step 13 − Get the return values.

  • Step 14 − Terminate the process.

Syntax of Comparing Streams to Loops

class Person {
	private String name;
	private int age;
	private String gender;
	private List<Person> siblings;
	public Person(String name, int age, String gender, List<Person> siblings) {
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.siblings = siblings;
	}
	public String getGender() {
		return gender;
	}
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public List<Person> getSiblings() {
		return siblings;
	}
}
private void streaming() {
	List<Person> persons = List.of();
	List<String> result = persons.stream()
	.filter(p -> p.getAge() > 18)
	.filter(p -> p.getAge() <= 65)
	.filter(p -> p.getName() != null)
	.filter(p -> p.getName().startsWith("B"))
	.map(p -> p.getName())
	.collect(Collectors.toList());
}

In this possible syntax above, we have tried to show you ho to create an input stream and compare it with anlther array list. By using these particular syntax mentioned above, we are heading towards some possible approaches related to the problem statement.

Approaches to Follow

  • Approach 1 − Java program to compare streams to loops by using java.io.IOException and creating a new list from an existing list

  • Approach 2 − Java program to show the execution of the code when exception is caused by the operation of comparing steram

Approach 1: to Compare Streams to Loops by Using Java.io.IOException and Creating a new List From an Existing List

Use of Java.io.IOException and Create a List From an Existing List

In this possible approach, we are going to use the java.io.IOException and further we will create a particular array list to get a new array list of the sorted elements as an output.

private void forLoop(){
	List<Person> persons = List.of();
	List<String> result = new ArrayList<>();
	for(Person p : persons){
		if(p.getAge() > 18 && p.getAge() <= 65 && p.getName() != null &&
		p.getName().startsWith("B")){
			result.add(p.getName());
		}
	}
}

Example 1

//Java Program to Compare Streams to Loops By Using java.io.IOException
import java.io.IOException;
import java.lang.String;
import java.nio.file.*;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.*;
public class ARBRDDKOLDHAKA {
   public static void main(String[] args)
   throws IOException{
      System.out.println("Integer Stream Is Here: ");
      IntStream.range(1, 20).forEach(System.out::print);
      System.out.println();
      System.out.println("Integer Stream Values With The Value Skip :");
      IntStream.range(1, 20).skip(5).forEach(
      x -> System.out.println(x));
      System.out.println();
      System.out.println("Integer Stream With Sum We Can Get: ");
      System.out.println(IntStream.range(1, 5).sum());
      System.out.println();
      System.out.println(
      "Stream.of, sorted and Find The First : ");
      Stream.of("Rudra ", "Aboni ", "2022 ")
      .sorted()
      .findFirst()
      .ifPresent(System.out::println);
      System.out.println();
      String[] names = { "India", "Bangladesh",
      "Dhaka", "Kolkata",
      "Esplanade", "Howrah Bridge",
      "DU", "Indira Road",
      "Kolkata Dhaka Cantt." };
      System.out.println(
      "Stream from Array, sort, filter and print : ");
      Arrays
      .stream(names)
      .filter(x -> x.startsWith("S"))
      .sorted()
      .forEach(System.out::println);
      System.out.println();
      System.out.println(
      "Average of squares of an int array : ");
      Arrays.stream(new int[] { 2, 4, 6, 8, 10 })
      .map(x -> x * x)
      .average()
      .ifPresent(System.out::println);
      System.out.println();
      System.out.println(
      "Stream from List, filter and print : ");
      List<String> people = Arrays.asList(
         "AI", "Matlab", "Scikit", "TensorFlow",
         "OpenCV", "DeepLearning", "NLP",
         "NeuralNetworks");
      people.stream()
      .map(String::toLowerCase)
      .filter(x -> x.startsWith("a"))
      .forEach(System.out::println);
      System.out.println();
      System.out.println("Reduction - sum : ");
      double total
      = Stream.of(7.3, 1.5, 4.8)
      .reduce(0.0,
      (Double a, Double b) -> a + b);
      System.out.println("Total = " + total);
      System.out.println();
      System.out.println(
      "Reduction - summary statistics : ");
      IntSummaryStatistics summary
      = IntStream.of(7, 2, 19, 88, 73, 4, 10)
      .summaryStatistics();
      System.out.println(summary);
      System.out.println();
   }
}

Output

Integer Stream Is Here:
12345678910111213141516171819
Integer Stream Values With The Value Skip :
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Integer Stream With Sum We Can Get:
10
Stream.of, sorted and Find The First :
2022
Stream from Array, sort, filter and print :
Average of squares of an int array :
44.0
Stream from List, filter and print :
ai
Reduction - sum :
Total = 13.600000000000001
Reduction - summary statistics :
IntSummaryStatistics{count=7, sum=203, min=2, average=29.000000, max=88}

In this particular Java approach, we are going to create a list first. By using that particular list we will compare the streams with some loops to get a new sorted data elements from that declared data set previously.

Example 2

//Java Program to Comparing Streams to Loops By Creating A New List From An Existing List
import java.util.*;
class ProgrammingLanguage {
   int rank;
   String name;
   int value;
   public ProgrammingLanguage(int rank, String name,
   int value){
      this.rank = rank;
      this.name = name;
      this.value = value;
   }
}
public class ARBRDD {
   public static void main(String[] args){
      List<ProgrammingLanguage> programmingLanguage
      = new ArrayList<ProgrammingLanguage>();
      programmingLanguage.add(
      new ProgrammingLanguage(1, "Java Programming",07102001 ));
      programmingLanguage.add(
      new ProgrammingLanguage(2, "Rust Programming", 16101997));
      programmingLanguage.add(
      new ProgrammingLanguage(3, "Ruby", 1500));
      programmingLanguage.add(
      new ProgrammingLanguage(4, "Scala", 2500));
      programmingLanguage.add(
      new ProgrammingLanguage(5, "Groovy", 4000));
      List<Integer> languageValueList
      = new ArrayList<Integer>();
      for (ProgrammingLanguage language :
      programmingLanguage) {
         if (language.value < 3000) {
            languageValueList.add(language.value);
         }
      }
      System.out.println(languageValueList);
   }
}

Output

[1500, 2500]

Approach 2: Execution of the Code When Exception is Caused by Comparing Steram

Use of Finally Block

In this approach, we are going to explain the possible exceptions can be occurred by a comparing stream when we open a file aka string and operate on it by using a loop. This is a fixing method on a steam exception, which helps the code to run successfully.

try {
	System.out.println("Open files");
	int a = 45;
	int b = 0;
	int div = a / b;
	System.out.println("STATEMENT" + div);
}

Example

//Java program to show the execution of the code when exception is caused by the operation of comparing steram
import java.io.*;
public class ARBRDD {
   public static void main(String[] args){
      try {
         System.out.println("Open files");
         int a = 45;
         int b = 0;
         int div = a / b;
         System.out.println("After dividing a and b ans is " + div);
      }
      catch (ArithmeticException ae) {
         System.out.println("exception caught");
         System.out.println(ae);
      }
      finally {
         System.out.println("Inside finally block after the stream comparison");
         System.out.println("Close files");
      }
   }
}

Output

Open files
exception caught
java.lang.ArithmeticException: / by zero
Inside finally block after the stream comparison
Close files

Conclusion

Comparing streams with the loops is a lightweight operation on an array which helps in the terms of a heap cinstruction and we can get a grip on the CPU usage. In this article today, we have tried to build some Java codes by using the above mentioned syntax and algorithm to solve the problem statement in an efficient manner.

Updated on: 27-Dec-2023

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements