- Prev Class
- Next Class
- No Frames
- All Classes
- Summary:
- Nested |
- Field |
- Constr |
- Detail:
Interface Stream<T>
- must be non-interfering (they do not modify the stream source); and
- in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).
Nested Class Summary
Method summary, methods inherited from interface java.util.stream. basestream, method detail, maptodouble, flatmaptoint, flatmaptolong, flatmaptodouble, foreachordered.
Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .
Scripting on this page tracks web page traffic, but does not change the content in any way.
- Skip to content
- Accessibility Policy
- QUICK LINKS
- Oracle Cloud Infrastructure
- Oracle Fusion Cloud Applications
- Oracle Database
- Download Java
- Careers at Oracle
- Create an Account
Processing Data with Java SE 8 Streams, Part 1
by Raoul-Gabriel Urma
Use stream operations to express sophisticated data processing queries.
What would you do without collections? Nearly every Java application makes and processes collections. They are fundamental to many programming tasks: they let you group and process data. For example, you might want to create a collection of banking transactions to represent a customer’s statement. Then, you might want to process the whole collection to find out how much money the customer spent. Despite their importance, processing collections is far from perfect in Java.
- Originally published in the March/April 2014 issue of Java Magazine . Subscribe today.
First, typical processing patterns on collections are similar to SQL-like operations such as “finding” (for example, find the transaction with highest value) or “grouping” (for example, group all transactions related to grocery shopping). Most databases let you specify such operations declaratively. For example, the following SQL query lets you find the transaction ID with the highest value: "SELECT id, MAX(value) from transactions" .
As you can see, we don’t need to implement how to calculate the maximum value (for example, using loops and a variable to track the highest value). We only express what we expect. This basic idea means that you need to worry less about how to explicitly implement such queries—it is handled for you. Why can’t we do something similar with collections? How many times do you find yourself reimplementing these operations using loops over and over again?
Second, how can we process really large collections efficiently? Ideally, to speed up the processing, you want to leverage multicore architectures. However, writing parallel code is hard and error-prone.
Java SE 8 to the rescue! The Java API designers are updating the API with a new abstraction called Stream that lets you process data in a declarative way. Furthermore, streams can leverage multi-core architectures without you having to write a single line of multithread code. Sounds good, doesn’t it? That’s what this series of articles will explore.
Here’s a mind-blowing idea: these two operations can produce elements “forever.”
Before we explore in detail what you can do with streams, let’s take a look at an example so you have a sense of the new programming style with Java SE 8 streams. Let’s say we need to find all transactions of type grocery and return a list of transaction IDs sorted in decreasing order of transaction value. In Java SE 7, we’d do that as shown in Listing 1 . In Java SE 8, we’d do it as shown in Listing 2 .
Figure 1 illustrates the Java SE 8 code. First, we obtain a stream from the list of transactions (the data) using the stream() method available on List . Next, several operations ( filter , sorted , map , collect ) are chained together to form a pipeline, which can be seen as forming a query on the data.
So how about parallelizing the code? In Java SE 8 it’s easy: just replace stream() with parallel Stream() , as shown in Listing 3 , and the Streams API will internally decompose your query to leverage the multiple cores on your computer.
Don’t worry if this code is slightly overwhelming. We will explore how it works in the next sections. However, notice the use of lambda expressions (for example, t-> t.getCategory() == Transaction.GROCERY ) and method references (for example, Transaction::getId ), which you should be familiar with by now. (To brush up on lambda expressions, refer to previous Java Magazine articles and other resources listed at the end of this article.)
For now, you can see a stream as an abstraction for expressing efficient, SQL-like operations on a collection of data. In addition, these operations can be succinctly parameterized with lambda expressions.
At the end of this series of articles about Java SE 8 streams, you will be able to use the Streams API to write code similar to Listing 3 to express powerful queries.
Getting Started with Streams
Let’s start with a bit of theory. What’s the definition of a stream? A short definition is “a sequence of elements from a source that supports aggregate operations.” Let’s break it down:
- Sequence of elements: A stream provides an interface to a sequenced set of values of a specific element type. However, streams don’t actually store elements; they are computed on demand.
- Source: Streams consume from a data-providing source such as collections, arrays, or I/O resources.
- Aggregate operations: Streams support SQL-like operations and common operations from functional programing languages, such as filter , map , reduce , find , match , sorted , and so on.
Furthermore, stream operations have two fundamental characteristics that make them very different from collection operations:
- Pipelining: Many stream operations return a stream themselves. This allows operations to be chained to form a larger pipeline. This enables certain optimizations, such as laziness and short-circuiting , which we explore later.
- Internal iteration: In contrast to collections, which are iterated explicitly ( external iteration ), stream operations do the iteration behind the scenes for you.
Let’s revisit our earlier code example to explain these ideas. Figure 2 illustrates Listing 2 in more detail.
We first get a stream from the list of transactions by calling the stream() method. The datasource is the list of transactions and will be providing a sequence of elements to the stream. Next, we apply a series of aggregate operations on the stream: filter (to filter elements given a predicate), sorted (to sort the elements given a comparator), and map (to extract information). All these operations except collect return a Stream so they can be chained to form a pipeline, which can be viewed as a query on the source.
No work is actually done until collect is invoked. The collect operation will start processing the pipeline to return a result (something that is not a Stream ; here, a List ). Don’t worry about collect for now; we will explore it in detail in a future article. At the moment, you can see collect as an operation that takes as an argument various recipes for accumulating the elements of a stream into a summary result. Here, toList() describes a recipe for converting a Stream into a List .
Before we explore the different methods available on a stream, it is good to pause and reflect on the conceptual difference between a stream and a collection.
Streams Versus Collections
Both the existing Java notion of collections and the new notion of streams provide interfaces to a sequence of elements. So what’s the difference? In a nutshell, collections are about data and streams are about computations.
Consider a movie stored on a DVD. This is a collection (perhaps of bytes or perhaps of frames—we don’t care which here) because it contains the whole data structure. Now consider watching the same video when it is being streamed over the internet. It is now a stream (of bytes or frames). The streaming video player needs to have downloaded only a few frames in advance of where the user is watching, so you can start displaying values from the beginning of the stream before most of the values in the stream have even been computed (consider streaming a live football game).
In the coarsest terms, the difference between collections and streams has to do with when things are computed. A collection is an in-memory data structure, which holds all the values that the data structure currently has—every element in the collection has to be computed before it can be added to the collection. In contrast, a stream is a conceptually fixed data structure in which elements are computed on demand.
Using the Collection interface requires iteration to be done by the user (for example, using the enhanced for loop called foreach ); this is called external iteration.
In contrast, the Streams library uses internal iteration—it does the iteration for you and takes care of storing the resulting stream value somewhere; you merely provide a function saying what’s to be done. The code in Listing 4 (external iteration with a collection) and Listing 5 (internal iteration with a stream) illustrates this difference.
In Listing 4 , we explicitly iterate the list of transactions sequentially to extract each transaction ID and add it to an accumulator. In contrast, when using a stream, there’s no explicit iteration. The code in Listing 5 builds a query, where the map operation is parameterized to extract the transaction IDs and the collect operation converts the resulting Stream into a List .
You should now have a good idea of what a stream is and what you can do with it. Let’s now look at the different operations supported by streams so you can express your own data processing queries.
Stream Operations: Exploiting Streams to Process Data
The Stream interface in java.util .stream.Stream defines many operations, which can be grouped in two categories. In the example illustrated in Figure 1 , you can see the following operations:
- filter , sorted , and map , which can be connected together to form a pipeline
- collect , which closed the pipeline and returned a result
Stream operations that can be connected are called intermediate operations . They can be connected together because their return type is a Stream . Operations that close a stream pipeline are called terminal operations . They produce a result from a pipeline such as a List , an Integer , or even void (any non- Stream type).
You might be wondering why the distinction is important. Well, intermediate operations do not perform any processing until a terminal operation is invoked on the stream pipeline; they are “lazy.” This is because intermediate operations can usually be “merged” and processed into a single pass by the terminal operation.
For example, consider the code in Listing 6 , which computes two even square numbers from a given list of numbers. You might be surprised that it prints the following:
This is because limit(2) uses short-circuiting ; we need to process only part of the stream, not all of it, to return a result. This is similar to evaluating a large Boolean expression chained with the and operator: as soon as one expression returns false , we can deduce that the whole expression is false without evaluating all of it. Here, the operation limit returns a stream of size 2 .
In addition, the operations filter and map have been merged in the same pass.
To summarize what we’ve learned so far, working with streams, in general, involves three things:
- A datasource (such as a collection) on which to perform a query
- A chain of intermediate operations, which form a stream pipeline
- One terminal operation, which executes the stream pipeline and produces a result
The Streams API will internally decompose your query to leverage the multiple cores on your computer.
Let’s now take a tour of some of the operations available on streams. Refer to the java.util .stream.Stream interface for the complete list, as well as to the resources at the end of this article for more examples.
Filtering. There are several operations that can be used to filter elements from a stream:
- filter(Predicate) : Takes a predicate ( java.util.function.Predicate ) as an argument and returns a stream including all elements that match the given predicate
- distinct : Returns a stream with unique elements (according to the implementation of equals for a stream element)
- limit(n) : Returns a stream that is no longer than the given size n
- skip(n) : Returns a stream with the first n number of elements discarded
Finding and matching. A common data processing pattern is determining whether some elements match a given property. You can use the anyMatch , allMatch , and noneMatch operations to help you do this. They all take a predicate as an argument and return a boolean as the result (they are, therefore, terminal operations). For example, you can use allMatch to check that all elements in a stream of transactions have a value higher than 100, as shown in Listing 7 .
In addition, the Stream interface provides the operations findFirst and findAny for retrieving arbitrary elements from a stream. They can be used in conjunction with other stream operations such as filter . Both findFirst and findAny return an Optional object, as shown in Listing 8 .
The Optional<T> class ( java.util .Optional ) is a container class to represent the existence or absence of a value. In Listing 8 , it is possible that findAny doesn’t find any transaction of type grocery . The Optional class contains several methods to test the existence of an element. For example, if a transaction is present, we can choose to apply an operation on the optional object by using the ifPresent method, as shown in Listing 9 (where we just print the transaction).
Mapping. Streams support the method map , which takes a function ( java.util.function.Function ) as an argument to project the elements of a stream into another form. The function is applied to each element, “mapping” it into a new element.
For example, you might want to use it to extract information from each element of a stream. In the example in Listing 10 , we return a list of the length of each word from a list. Reducing. So far, the terminal operations we’ve seen return a boolean ( allMatch and so on), void ( forEach ), or an Optional object ( findAny and so on). We have also been using collect to combine all elements in a Stream into a List .
However, you can also combine all elements in a stream to formulate more-complicated process queries, such as “what is the transaction with the highest ID?” or “calculate the sum of all transactions’ values.” This is possible using the reduce operation on streams, which repeatedly applies an operation (for example, adding two numbers) on each element until a result is produced. It’s often called a fold operation in functional programming because you can view this operation as “folding” repeatedly a long piece of paper (your stream) until it forms one little square, which is the result of the fold operation.
It helps to first look at how we could calculate the sum of a list using a for loop:
Each element of the list of numbers is combined iteratively using the addition operator to produce a result. We essentially “reduced” the list of numbers into one number. There are two parameters in this code: the initial value of the sum variable, in this case 0 , and the operation for combining all the elements of the list, in this case + .
Using the reduce method on streams, we can sum all the elements of a stream as shown in Listing 11 . The reduce method takes two arguments:
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
Listing 11
- An initial value, here 0
- A BinaryOperator<T> to combine two elements and produce a new value
The reduce method essentially abstracts the pattern of repeated application. Other queries such as “calculate the product” or “calculate the maximum” (see Listing 12 ) become special use cases of the reduce method.
Numeric Streams
You have just seen that you can use the reduce method to calculate the sum of a stream of integers. However, there’s a cost: we perform many boxing operations to repeatedly add Integer objects together. Wouldn’t it be nicer if we could call a sum method, as shown in Listing 13 , to be more explicit about the intent of our code?
Java SE 8 introduces three primitive specialized stream interfaces to tackle this issue— IntStream , DoubleStream , and LongStream —that respectively specialize the elements of a stream to be int , double , and long .
The most-common methods you will use to convert a stream to a specialized version are mapToInt , mapToDouble , and mapToLong . These methods work exactly like the method map that we saw earlier, but they return a specialized stream instead of a Stream<T> . For example, we could improve the code in Listing 13 as shown in Listing 14 . You can also convert from a primitive stream to a stream of objects using the boxed operation.
Finally, another useful form of numeric streams is numeric ranges. For example, you might want to generate all numbers between 1 and 100. Java SE 8 introduces two static methods available on IntStream , DoubleStream , and LongStream to help generate such ranges: range and rangeClosed .
Both methods take the starting value of the range as the first parameter and the end value of the range as the second parameter. However, range is exclusive, whereas rangeClosed is inclusive. Listing 15 is an example that uses rangeClosed to return a stream of all odd numbers between 10 and 30.
Building Streams
There are several ways to build streams. You’ve seen how you can get a stream from a collection. Moreover, we played with streams of numbers. You can also create streams from values, an array, or a file. In addition, you can even generate a stream from a function to produce infinite streams!
Creating a stream from values or from an array is straightforward: just use the static methods Stream .of for values and Arrays.stream for an array, as shown in Listing 16 .
In contrast to collections, which are iterated explicitly ( external iteration ), stream operations do the iteration behind the scenes for you.
You can also convert a file in a stream of lines using the Files.lines static method. For example, in Listing 17 we count the number of lines in a file.
Infinite streams. Finally, here’s a mind-blowing idea before we conclude this first article about streams. By now you should understand that elements of a stream are produced on demand. There are two static methods— Stream.iterate and Stream .generate —that let you create a stream from a function. However, because elements are calculated on demand, these two operations can produce elements “forever.” This is what we call an infinite stream : a stream that doesn’t have a fixed size, as a stream does when we create it from a fixed collection.
- Java 8 Lambdas in Action
- GitHub repository with Java SE 8 code examples
- “ Java 8: Lambdas, Part 1 ” by Ted Neward
Listing 18 is an example that uses iterate to create a stream of all numbers that are multiples of 10. The iterate method takes an initial value (here, 0 ) and a lambda (of type UnaryOperator<T> ) to apply successively on each new value produced.
Stream<Integer> numbers = Stream.iterate(0, n -> n + 10);
We can turn an infinite stream into a fixed-size stream using the limit operation. For example, we can limit the size of the stream to 5, as shown in Listing 19 .
numbers.limit(5).forEach(System.out::println); // 0, 10, 20, 30, 40
Java SE 8 introduces the Streams API, which lets you express sophisticated data processing queries. In this article, you’ve seen that a stream supports many operations such as filter , map , reduce , and iterate that can be combined to write concise and expressive data processing queries. This new way of writing code is very different from how you would process collections before Java SE 8. However, it has many benefits. First, the Streams API makes use of several techniques such as laziness and short-circuiting to optimize your data processing queries. Second, streams can be parallelized automatically to leverage multicore architectures. In the next article in this series, we will explore more-advanced operations, such as flatMap and collect . Stay tuned.
Java Arrays
Java strings.
- Java Collection
- Java 8 Tutorial
Java Multithreading
Java exception handling.
- Java Programs
- Java Project
- Java Collections Interview
Java Interview Questions
- Spring Boot
Java 8 Stream Tutorial
Java 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the elements.
The stream can be used by importing java.util.stream package. Stream API is used to process collections of objects. Streams are designed to be efficient and can support improving your program’s performance by allowing you to avoid unnecessary loops and iterations. Streams can be used for filtering, collecting, printing, and converting from one data structure to another, etc.
This Java 8 Stream Tutorial will cover all the basic to advanced concepts of Java 8 stream like Java 8 filter and collect operations, and real-life examples of Java 8 streams.
Prerequisites for Java Stream
Before proceeding to Java 8 , it’s recommended to have a basic knowledge of Java 8 and its important concepts such as lambda expression, Optional, method references, etc.
Note: If we want to represent a group of objects as a single entity then we should go for collection . But if we want to process objects from the collection then we should go for streams.
If we want to use the concept of streams then stream() is the method to be used. Stream is available as an interface.
In the above pre-tag, ‘c’ refers to the collection. So on the collection, we are calling the stream() method and at the same time, we are storing it as the Stream object. Henceforth, this way we are getting the Stream object.
Note: Streams are present in java’s utility package named java.util.stream
Let us now start with the basic components involved in streams. They as listed as follows:
- Sequence of Elements
- Aggregate Operations
- Internal iteration
Features of Java Stream
- A stream is not a data structure instead it takes input from the Collections , Arrays , or I/O channels .
- Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
- Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Before moving ahead in the concept consider an example in which we are having ArrayList of integers, and we suppose we apply a filter to get only even numbers from the object inserted.
How does Stream Work Internally?
In streams,
- To filter out from the objects we do have a function named filter()
- To impose a condition we do have a logic of predicate which is nothing but a functional interface. Here function interface can be replaced by a random expression. Hence, we can directly impose the condition check-in our predicate.
- To collect elements we will be using Collectors.toList() to collect all the required elements.
- Lastly, we will store these elements in a List and display the outputs on the console.
Explanation of the above program:
In our collection object, we were having elements entered using the add() operation. After processing the object in which they were stored through streams we impose a condition in the predicate of streams to get only even elements, we get elements in the object as per our requirement. Hence, streams helped us this way in processing over-processed collection objects.
Various Core Operations Over Streams
There are broadly 3 types of operations that are carried over streams namely as follows as depicted from the image shown above:
- Intermediate operations
- Terminal operations
- Short-circuit operations
Let us do discuss out intermediate operations here only in streams to a certain depth with the help of an example in order to figure out other operations via theoretical means.
1. Intermediate Operations:
Intermediate operations transform a stream into another stream. Some common intermediate operations include:
- filter(): Filters elements based on a specified condition.
- map(): Transforms each element in a stream to another value.
- sorted(): Sorts the elements of a stream.
All three of them are discussed below as they go hand in hand in nearly most of the scenarios and to provide better understanding by using them later by implementing in our clean Java programs below. As we already have studied in the above example of which we are trying to filter processed objects can be interpreted as filter() operation operated over streams.
2. Terminal Operations
Terminal Operations are the operations that on execution return a final result as an absolute value.
- collect(): It is used to return the result of the intermediate operations performed on the stream.
- forEach(): It iterates all the elements in a stream.
- reduce(): It is used to reduce the elements of a stream to a single value.
3. Short Circuit Operations
Short-circuit operations provide performance benefits by avoiding unnecessary computations when the desired result can be obtained early. They are particularly useful when working with large or infinite streams.
- anyMatch(): it checks the stream if it satisfies the given condition.
- findFirst(): it checks the element that matches a given condition and stops processing when it finds it.
Note: They are lazy, meaning they are not executed until a terminal operation is invoked.
Later on from that processed filtered elements of objects, we are collecting the elements back to List using Collectors for which we have imported a specific package named java.util.stream with the help of Collectors.toList() method. This is referred to as collect() operation in streams so here again we won’t be taking an example to discuss them out separately.
Note: For every object if there is urgency to do some operations be it square, double or any other than only we need to use map() function operation else try to use filter() function operation.
Lazy Evaluation
Lazy Evaluation is the concept in Java Streams where computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. It is called lazy because intermediate operations are not evaluated unless a terminal operation is invoked.
Now geeks you are well aware of ‘why’ streams were introduced, but you should be wondering ‘where’ to use them. The answer is very simple as we do use them too often in our day-to-day life. Hence, the geek in simpler words we say directly lands p on wherever the concept of the collection is applicable, stream concept can be applied there.
Java Stream: Real-life Examples
In general, daily world, whenever the data is fetched from the database, it is more likely we will be using collection so there stream concept is must apply to deal with processed data.
Now we will be discussing real-time examples to interrelate streams in our life. Here we will be taking the most widely used namely as follows:
- Streams in a Grocery store
- Streams in mobile networking
1. Streams in a Grocery store
The above pictorial image has been provided is implemented in streams which are as follows:
2. Streams in mobile networking
Similarly, we can go for another widely used concept which is our dealing with our mobile numbers. Here we will not be proposing listings, simply will be demonstrating how the stream concept is invoked in mobile networking by various service providers across the globe.
Collection can hold any number of object so let ‘mobileNumber’ be a collection and let it be holding various mobile numbers say it be holding 100+ numbers as objects. Suppose now the only carrier named ‘Airtel’ whom with which we are supposed to send a message if there is any migration between states in a country. So here streams concept is applied as if while dealing with all mobile numbers we will look out for this carrier using the filter() method operation of streams. In this way, we are able to deliver the messages without looking out for all mobile numbers and then delivering the message which senses impractical if done so as by now we are already too late to deliver. In this way these intermediate operations namely filter(), collect(), map() help out in the real world. Processing becomes super simpler which is the necessity of today’s digital world.
Hope by now you the users come to realize the power of streams in Java as if we have to do the same task we do need to map corresponding to every object, increasing in code length, and decreasing the optimality of our code. With the usage of streams, we are able to in a single line irrespective of elements contained in the object as with the concept of streams we are dealing with the object itself.
Note: filter, sorted, and map, which can be connected together to form a pipeline.
What is a Pipeline?
A Stream Pipeline is a concept of chaining operations together Terminal Operations and Intermediate Operations. A Pipeline contains a stream source, which is further followed by zero or more intermediate operations, and a terminal operation.
Java Stream Operations
Method types and pipelines.
Methods are of two types in Stream as mentioned below:
Terminal Operations
Intermediate operations.
These are the operations that after consumed can’t further be used. There are few operations mentioned below:
forEach performs an action for each element of the stream. Stream forEach is a terminal operation .
Stream toArray() returns an array containing the elements of this stream. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
3. min and max
min and max return the min and max elements from the stream.
Where, Optional is a container object which may or may not contain a non-null value, and T is the type of object that may be compared by this comparator.
It returns a new stream that can be further processed. There are certain operations mentioned below:
Stream filter returns a stream consisting of the elements of this stream that match the given predicate.
2. distinct
distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface.
Where Stream is an interface and the function returns a stream consisting of distinct elements.
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.
where Stream is an interface and T is the type of stream elements.
Comparison-Based Stream Operations
Comparison Based Stream Operations are the used for comparing, sorting, and ordering elements within a stream. There are certain examples of Comparison Based Stream Operations mentioned below:
- min and max
Java Stream Specializations
As there are primitive data types or specializations like int, long and double. Similarly, streams have IntStream, LongStream, and DoubleStream. These are convenient for making performing transactions with numerical primitives.
1. Specialized Operations
Specialized streams provide additional operations as compared to the standard Stream – which are quite convenient when dealing with numbers.
2. Reduction Operations
Reduce Operation applies a binary operator, it takes a sequence of input elements and combines them to a single summary result. It is all done where first argument to the operator is the return value of the previous application and second argument is the current stream element.
Parallel Streams
Parallel Streams are the type of streams that can perform operations concurrently on multiple threads. These Streams are meant to make use of multiple processors or cores available to speed us the processing speed. There are two methods to create parallel streams are mentioned below:
- Using the parallel() method on a stream
- Using parallelStream() on a Collection
To know more about Parallel Streams refer to this link .
Infinite Streams
Infinite Streams are the type of Streams that can produce unbounded(Infnite) number of elements. These Streams are useful when you need to work with the data sources that are not finite.
Java Stream: File Operation
In this section, we see how to utilize Java stream in file I/O operation.
1. File Read Operation
Let’s understand file read operation through the given example
2. File Write Operation
Let’s understand file write operation through the given example
Java Streams Improvements in Java 9
As we know, Java 8 introduced a Java stream to the world which provided a powerful way to process collections of data. However, the following version of the language also contributed to the feature. Thereafter, some improvements and features were added to the Java stream in JAVA 9. In this section, we will provide an overview of the advancements introduced by Java 9 to the Streams API like takeWhile, dropWhile, iterate, ofNullable, etc.
Java Streams offer a powerful way to handle data in Java. They allow developers to write more readable and concise code for processing collections. By using Java Streams, you can easily filter, map, and reduce data with simple and expressive methods. This not only makes your code easier to maintain but also helps improve performance by taking advantage of parallel processing. If you’re looking to make your data operations more efficient and straightforward, learning Java Streams is definitely worth the effort.
Java 8 Stream – FAQs
1. how to learn streams in java 8.
To learn java streams effectivily you need to get you theory concepets as well as practical skills strong. for that first you need to make your concepts strong then make it in pratice. Grasp the fundamental concept of streams. What are streams? Why are they useful? How do they work? Familiarize yourself with creating streams from diverse sources. How can you create a stream from an array, a collection, or a file? Dive into intermediate operations. What are intermediate operations? How do they transform data? Understand terminal operations. What are terminal operations? How do they produce final results or trigger actions on the stream? Embrace the concept of lazy evaluation. How does lazy evaluation work? How does it optimize resource usage? Practice chaining operations to create intricate data pipelines. How can you chain multiple operations together to create complex data pipelines? Explore parallel processing. How can you use parallel processing to improve the performance of your streams? Apply streams to real-world scenarios. Find situations where streams can simplify code and improve efficiency. Utilize online resources, tutorials, and exercises. Consider in-depth tutorials. If you want a comprehensive learning experience, consider taking an in-depth tutorial on streams.
2. Why we use stream in Java 8?
Java streams offer a range of functionalities that significantly enhance their importance. Efficient Data Processing: They don’t store the data themselves, but instead act as a way to process data from various DS . Functional and Non-Destructive : Streams follow a functional programming approach. Lazy Evaluation : which means they perform computations only when needed Single Pass Processing : The elements in a stream are processed only once during its lifetime
3. What is the best practice of Java streams?
Java Stream API is a powerful and flexible tool that can significantly simplify code for data processing tasks and here are some best pratices for using java streams. Use primitive streams for better performance Avoid nesting streams use stream with immutable objects Use filter() before map() to avoid unnecessary processing Prefer method references over lambda expressions Use distinct() to remove duplicates Use sorted() with caution Use lazy evaluation for better performance
Similar Reads
- Java Tutorial Java is one of the most popular and widely used programming languages which is used to develop mobile apps, desktop apps, web apps, web servers, games, and enterprise-level systems. Java was invented by James Gosling and Oracle currently owns it. JDK 23 is the latest version of Java. Popular platfor 4 min read
Java Overview
- Introduction to Java Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the 10 min read
- The Complete History of Java Programming Language Java is an Object-Oriented programming language developed by James Gosling in the early 1990s. The team initiated this project to develop a language for digital devices such as set-top boxes, television, etc. Originally C++ was considered to be used in the project but the idea was rejected for sever 5 min read
- How to Download and Install Java for 64 bit machine? Java is one of the most popular and widely used programming languages. It is a simple, portable, platform-independent language. It has been one of the most popular programming languages for many years. In this article, We will see How to download and install Java for Windows 64-bit. We'll also be an 4 min read
- Setting up the environment in Java Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 22. Below are the environ 6 min read
- How JVM Works - JVM Architecture JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one s 7 min read
- JDK in Java The Java Development Kit (JDK) is a cross-platformed software development environment that offers a collection of tools and libraries necessary for developing Java-based software applications and applets. It is a core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java 5 min read
- Differences between JDK, JRE and JVM Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java 5 min read
Java Basics
- Java Syntax Java is an object-oriented programming language which is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++ which makes it easier to understand. Let's understand the Syntax and Structure of Java Programs with a basic 5 min read
- Java Hello World Program Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn h 5 min read
- Java Identifiers An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names and every Java Variables must be identified with unique names. Example: public class Test{ public static void main(String[] args) { int a = 20; }}In the above Java code, we h 2 min read
- Java Keywords In Java, Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. If we do we will get a compile-time error as shown below as follows: Example of Jav 5 min read
- Java Data Types Java is statically typed and also a strongly typed language because, in Java, each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with 11 min read
- Java Variables Variables are the containers for storing the data values or you can also call it a memory location name for the data. Every variable has a: Data Type - The kind of data that it can hold. For example, int, string, float, char, etc.Variable Name - To identify the variable uniquely within the scope.Val 8 min read
- Scope of Variables In Java Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of function call stack. Java programs are organized in the form of cla 5 min read
- Operators in Java Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types. What are the Java Operators?Operators in Java are the symbols used for performing 15 min read
- How to Take Input From User in Java? Java brings various Streams with its I/O package that helps the user perform all the Java input-output operations. These streams support all types of objects, data types, characters, files, etc. to fully execute the I/O operations. Input in Java can be with certain methods mentioned below in the art 5 min read
Java Flow Control
- Java if statement The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not. Example: [GFGTABS] Java // Java program to ill 5 min read
- Java if-else Decision-making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. In this article, we will learn 3 min read
- Java if-else-if ladder with Examples Decision Making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions.Java if-else-if ladder is used to decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is 3 min read
- For Loop in Java Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure 7 min read
- For-each loop in Java The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required. Example: Below is a basic e 6 min read
- Java while Loop Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGT 3 min read
- Java Do While Loop Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // 4 min read
- Break statement in Java Break Statement is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax: break;Basically, break state 3 min read
- Continue Statement in Java Suppose a person wants code to execute for the values as per the code is designed to be executed but forcefully the same user wants to skip out the execution for which code should have been executed as designed above but will not as per the demand of the user. In simpler words, it is a decision-maki 6 min read
- return keyword in Java In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows: Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrat 6 min read
Java Methods
- Java Methods The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every metho 10 min read
- How to Call Method in Java Java Methods are the collection of statements used for performing certain tasks and for returning the end result to the user.Java Methods enables the reuse the code without retyping the code. Every class in Java has its own methods, either inherited methods or user-defined methods that are used to d 4 min read
- Static methods vs Instance methods in Java In this article, we are going to learn about Static Methods and Instance Methods in Java. Java Instance MethodsInstance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the m 5 min read
- Access Modifiers in Java in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc to the user depending upon the access modifier used with the element. Let us learn about Java Access Modifiers, their types, and the uses of access 6 min read
- Command Line Arguments in Java Java command-line argument is an argument i.e. passed at the time of running the Java program. In Java, the command line arguments passed from the console can be received in the Java program and they can be used as input. The users can pass the arguments during the execution bypassing the command-li 3 min read
- Variable Arguments (Varargs) in Java Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments. Need of Java VarargsUntil JDK 4, we cant declare a method with variable no. of arguments. If the 4 min read
- Arrays in Java Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with e 15+ min read
- How to Initialize an Array in Java? An array in Java is a data structure used to store multiple values of the same data type. Each element in an array has a unique index value. It makes it easy to access individual elements. In an array, we have to declare its size first because the size of the array is fixed. In an array, we can stor 6 min read
- Java Multi-Dimensional Arrays A multidimensional array can be defined as an array of arrays. Data in multidimensional arrays are stored in tabular form (row-major order). Example: [GFGTABS] Java // Java Program to Demonstrate // Multi Dimensional Array import java.io.*; public class Main { public static void main(String[] args) 9 min read
- Jagged Array in Java Prerequisite: Arrays in Java A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays. Pictorial representation of Jagged array in M 5 min read
- Arrays class in Java The Arrays class in java.util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself. The c 13 min read
- Final Arrays in Java As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another 4 min read
- Strings in Java In Java, a String is an object that represents a sequence of characters. Java provides a robust and flexible API for handling strings, allowing for various operations such as concatenation, comparison, and manipulation. In this article, we will go through the Java String concept in detail. What are 9 min read
- Why Java Strings are Immutable? In Java, strings are immutable means their values cannot be changed once they are created. This feature enhances performance, security, and thread safety. In this article, we will explain why strings are immutable in Java and how this benefits Java applications. What Does Immutable Mean?An immutable 3 min read
- Java String concat() Method with Examples The string concat() method concatenates (appends) a string to the end of another string. It returns the combined string. It is used for string concatenation in Java. It returns NullPointerException if any one of the strings is Null. In this article, we will learn how to concatenate two strings in Ja 4 min read
- String class in Java String is a sequence of characters. In Java, objects of the String class are immutable which means they cannot be changed once created. In this article, we will learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import java.io.*; 7 min read
- StringBuffer class in Java StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time. Here are some important features and methods of the StringBuffer class 13 min read
- StringBuilder Class in Java with Examples StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much s 6 min read
- String vs StringBuilder vs StringBuffer in Java A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. Initializing a String is one of the important pillars required as a pre-requisite with deeper understanding. Comparison between String, StringBuilder, and StringB 7 min read
Java OOPs Concepts
- Object Oriented Programming (OOPs) Concept in Java As the name suggests, Object-Oriented Programming or Java OOPs concept refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks you assign. Object-oriented programmin 12 min read
- Classes and Objects in Java In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named 11 min read
- Java Constructors Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attrib 8 min read
- Object Class in Java Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class metho 7 min read
- Abstraction in Java Abstraction in Java is the process in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. In this article, we will learn about abstraction and what abstraction means. Simple Example to understand Abstraction:Televisi 11 min read
- Encapsulation in Java Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. Java Encapsulation is a way of hiding the implementation details of a class from outsid 8 min read
- Inheritance in Java Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from ano 13 min read
- Polymorphism in Java The word 'polymorphism' means 'having many forms'. In simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type. Real-life Illustration of Polymorphism in Java: A person can have d 6 min read
- Method Overloading in Java In Java, Method Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or a mixture of both. Method overloading in Java is also known as Compile-time Polymorphism, Static Polym 9 min read
- Overriding in Java In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or 13 min read
- Packages In Java Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.EmployeeMaking searching/locatin 8 min read
Java Interfaces
- Interfaces in Java An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to ac 11 min read
- Interfaces and Inheritance in Java A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This mean 7 min read
- Differences between Interface and Class in Java This article highlights the differences between a class and an interface in Java. They seem syntactically similar, both containing methods and variables, but they are different in many aspects. Differences between a Class and an Interface The following table lists all the major differences between a 4 min read
- Functional Interfaces in Java Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simp 10 min read
- Nested Interface in Java We can declare interfaces as members of a class or another interface. Such an interface is called a member interface or nested interface. Interfaces declared outside any class can have only public and default (package-private) access specifiers. In Java, nested interfaces (interfaces declared inside 5 min read
- Marker interface in Java It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. public interface Serializable { // nothing here } Examples of Marker Interface which are used in real-time applications : Cloneabl 3 min read
- Comparator Interface in Java with Examples A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):Suppose we have an Array/ArrayList of our own class 6 min read
Java Collections
- Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac 15+ min read
- Collections Class in Java Collections class in Java is one of the utility classes in Java Collections Framework. The java.util package contains the Collections class in Java. Java Collections class is used with the static methods that operate on the collections or return the collection. All the methods of this class throw th 14 min read
- Collection Interface in Java with Examples The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subint 8 min read
- Java List Interface The List Interface in Java extends the Collection Interface and is a part of java.util package. It is used to store the ordered collections of elements. So in a Java List, you can organize and manage the data sequentially. Maintained the order of elements in which they are added.Allows the duplicate 15+ min read
- ArrayList in Java Java ArrayList is a part of collections framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in array is required. The main advantage of ArrayList is, unli 10 min read
- Vector Class in Java The Vector class implements a growable array of objects. Vectors fall in legacy classes, but now it is fully compatible with collections. It is found in java.util package and implement the List interface. Thread-Safe: All methods are synchronized, making it suitable for multi-threaded environments. 13 min read
- LinkedList in Java Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr 13 min read
- Stack Class in Java Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of LIFO(last-in-first-out). In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The Stack cl 11 min read
- Set in Java The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of the dupl 14 min read
- Java HashSet HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashTable internally.Also implements Serializable and Cloneable interfaces.HashSet is not thread-safe. 12 min read
- TreeSet in Java TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ 13 min read
- LinkedHashSet in Java with Examples Let us start with a simple Java code snippet that demonstrates how to create a LinkedHashSet object without adding any elements to it: [GFGTABS] Java import java.util.LinkedHashSet; public class LinkedHashSetCreation { public static void main(String[] args) { // Create a LinkedHashSet of Strings Lin 9 min read
- Queue Interface In Java The Queue Interface is present in java.util package and extends the Collection interface. It stores and processes the data in FIFO(First In First Out) order. It is an ordered list of objects limited to inserting elements at the end of the list and deleting elements from the start of the list. No Nul 13 min read
- PriorityQueue in Java The PriorityQueue class in Java is part of the java.util package. It is known that a Queue follows the FIFO(First-In-First-Out) Algorithm, but the elements of the Queue are needed to be processed according to the priority, that's when the PriorityQueue comes into play. The PriorityQueue is based on 11 min read
- Deque interface in Java with Example Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/ 10 min read
- Map Interface in Java In Java, Map Interface is present in java.util package represents a mapping between a key and a value. Java Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. No Duplicates in Keys: Ensures that keys are unique. H 12 min read
- HashMap in Java In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding 15+ min read
- LinkedHashMap in Java Let us start with a simple Java code snippet that demonstrates how to create and use a LinkedHashMap in Java. [GFGTABS] Java import java.util.LinkedHashMap; public class LinkedHashMapCreation { public static void main(String[] args) { // Create a LinkedHashMap of Strings (keys) and Integers (values) 9 min read
- Hashtable in Java Let us start with a simple Java code snippet that demonstrates how to create and use a HashTable. [GFGTABS] Java import java.util.Hashtable; public class HashtableCreation { public static void main(String args[]) { // Create a Hashtable of String keys and Integer values Hashtable<String, Integer 14 min read
- Java.util.Dictionary Class in Java The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface sinc 7 min read
- SortedSet Interface in Java with Examples The SortedSet interface is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this 8 min read
- Comparable Interface in Java with Examples The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo method that tak 4 min read
- Comparable vs Comparator in Java Java provides two interfaces to sort objects using data members of the class: ComparableComparatorUsing Comparable Interface A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider 6 min read
- Iterators in Java A Java Cursor is an Iterator, that is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one. In this article, we will learn about Java Iterators and it's working. Types of Cursors in JavaThere are three cursors in Java as mentioned below: IteratorEnumerationList 14 min read
- Exceptions in Java Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. What are Ja 10 min read
- Checked vs Unchecked Exceptions in Java In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked exceptionsUnchecked exceptions Understanding the difference betwee 5 min read
- Java Try Catch Block In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, 4 min read
- final, finally and finalize in Java This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different 13 min read
- throw and throws in Java In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as NullPointerException, ArrayIndexOutOfBoundsException, etc. In this article, we will 4 min read
- User-defined Custom Exception in Java An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which ar 3 min read
- Chained Exceptions in Java Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O err 3 min read
- Null Pointer Exception In Java NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Reason for Null Pointer ExceptionThese are certain reasons for Null Pointer Exc 6 min read
- Exception Handling with Method Overriding in Java An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-orient 6 min read
- Java Multithreading Tutorial Threads are the backbone of multithreading. We are living in a real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking ef 15+ min read
- Java Threads Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time). For example, in MS Word. one thread automatically formats 9 min read
- Java.lang.Thread Class in Java Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls in order to manage the behavior of 8 min read
- Runnable interface in Java java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread - Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run( 3 min read
- Lifecycle and States of a Thread in Java A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant: New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram shown below represents various states of a thread at any inst 6 min read
- Main thread in Java Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i 4 min read
- Java Thread Priority in Multithreading As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be give 5 min read
- Naming a thread and fetching name of current thread in Java Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a 5 min read
- Difference between Thread.start() and Thread.run() in Java In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. 3 min read
- Thread.sleep() Method in Java With Examples Thread Class is a class that is basically a thread of execution of the programs. It is present in Java.lang package. Thread class contains the Sleep() method. There are two overloaded methods of Sleep() method present in Thread Class, one is with one argument and another one is with two arguments. T 4 min read
- Daemon Thread in Java In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual M 4 min read
- Thread Safety and how to achieve it in Java As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already wor 5 min read
- Thread Pools in Java Background Server Programs such as database and web servers repeatedly execute requests from multiple clients and these are oriented around processing a large number of short tasks. An approach for building a server application would be to create a new thread each time a request arrives and service 9 min read
Java File Handling
- File Handling in Java In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file. Why File Handling is Required? File Handling is an integral part of any programming lan 7 min read
- Java.io.File Class in Java Java File class is Java's representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, 6 min read
- Java Program to Create a New File A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is created. The file is one way, in which data will be stored as per requirement. Steps to Create a N 8 min read
- Java Program to Write into a File In this article, we will see different ways of writing into a File using Java Programming language. Java FileWriter class in java is used to write character-oriented data to a file as this class is character-oriented class because of what it is used in file handling in java. There are many ways to 7 min read
- Delete a File Using Java Java provides methods to delete files using java programs. On contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin. Methods used to delete a file in Java: 1. Using java.io.File.de 2 min read
- Java IO FileReader Class FileReader in Java is a class in the java.io package which can be used to read a stream of characters from the files. Java IO FileReader class uses either specified charset or the platform's default charset for decoding from bytes to characters. 1. Charset: The Charset class is used to define method 3 min read
- FileWriter Class in Java Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java. This class inherits from OutputStreamWriter class which in turn 7 min read
- Java.io.FilePermission Class in Java java.io.FilePermission class is used to represent access to a file or a directory. These accesses are in the form of a path name and a set of actions associated to the path name(specifies which file to be open along with the extension and the path). For Example, in FilePermission("GEEKS.txt", "read" 5 min read
- Java.io.FileDescriptor in Java java.io.FileDescriptor works for opening a file having a specific name. If there is any content present in that file it will first erase all that content and put "Beginning of Process" as the first line. Instances of the file descriptor class serve as an opaque handle to the underlying machine-speci 4 min read
Java Streams and Lambda Expressions
- Lambda Expression in Java Lambda expressions in Java, introduced in Java SE 8, represent instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Functionalities of Lambda Expression in JavaLambda Expressi 5 min read
- Method References in Java with examples Functional Interfaces in Java and Lambda Function are prerequisites required in order to grasp grip over method references in Java. As we all know that a method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task 9 min read
- Java 8 Stream Tutorial Java 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme 15+ min read
- Java 8 Features - Complete Tutorial Java 8 is the most awaited release of Java programming language development because, in the entire history of Java, it never released that many major features. It consists of major features of Java. It is a new version of Java and was released by Oracle on 18 March 2014. Java provided support for fu 9 min read
- Java IO : Input-output in Java with Examples Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 sta 6 min read
- Java.io.Reader class in Java Java Reader class is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or 5 min read
- Java.io.Writer Class in Java java.io.Writer class is an abstract class. It is used to write to character streams. Declaration of Writer Class in Javapublic abstract class Writer extends Object implements Appendable, Closeable, FlushableConstructors of Java Writer Classprotected Writer(): Creates a new character stream that can 6 min read
- Java.io.FileInputStream Class in Java FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Constructors of FileInputStream Class 1. FileInputStream(File file): 3 min read
- FileOutputStream in Java FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a file, we use FileOutputStream class. For writing byte-oriented and character-oriented data, we can use FileOutpu 5 min read
- Ways to read input from console in Java In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassThis is the Java classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamRe 5 min read
- Java.io.BufferedOutputStream class in Java Java.io.BufferedInputStream class in Java Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. Fie 2 min read
- Difference Between Scanner and BufferedReader Class in Java In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner class is a simple text scanner that can parse primitive types and strings. It internally uses regular expressions to read different types while on the other hand BufferedReader class reads text from a 3 min read
- Fast I/O in Java in Competitive Programming Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow. In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC. Example: Input:7 31 7 min read
Java Synchronization
- Synchronization in Java Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results. Why use Java Synchronization?Java Synchronization is used to make sure by some synchronization method that only one thread can access th 5 min read
- Importance of Thread Synchronization in Java Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes 10 min read
- Method and Block Synchronization in Java Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent the 7 min read
- Difference Between Atomic, Volatile and Synchronized in Java Synchronized is the modifier applicable only for methods and blocks but not for the variables and for classes. There may be a chance of data inconsistency problem to overcome this problem we should go for a synchronized keyword when multiple threads are trying to operate simultaneously on the same j 5 min read
- Lock framework vs Thread synchronization in Java Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. T 5 min read
- Deadlock in Java Multithreading synchronized keyword is used to make the class or method thread-safe which means only one thread can have the lock of the synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock. It is important to use if our program is running in a mul 7 min read
- Deadlock Prevention And Avoidance When two or more processes try to access the critical section at the same time and they fail to access simultaneously or stuck while accessing the critical section then this condition is known as Deadlock. Deadlock prevention and avoidance are strategies used in computer systems to ensure that diffe 6 min read
- Difference Between Lock and Monitor in Java Concurrency Java Concurrency basically deals with concepts like multithreading and other concurrent operations. This is done to ensure maximum and efficient utilization of CPU performance thereby reducing its idle time in general. Locks have been in existence to implement multithreading much before the monitors 5 min read
- Reentrant Lock in Java Background The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don't offer any 9 min read
- Regular Expressions in Java In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi 8 min read
- Pattern pattern() method in Java with Examples The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not 2 min read
- Matcher pattern() method in Java with Examples The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax: public Pattern pattern() Parameters: This method do not accepts any parameter. Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher. Below examples illust 2 min read
- java.lang.Character class methods | Set 1 [caption id="attachment_151090" align="aligncenter" width="787"] lang.Character class wraps the value of a primitive data type - char to an object of datatype char and this object contains a single field having the data type - char. This class provides no. of methods regarding character manipulation 7 min read
- Quantifiers in Java Prerequisite: Regular Expressions in Java Quantifiers in Java allow users to specify the number of occurrences to match against. Below are some commonly used quantifiers in Java. X* Zero or more occurrences of X X? Zero or One occurrences of X X+ One or More occurrences of X X{n} Exactly n occurrenc 4 min read
Java Networking
- Java Networking When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is 15+ min read
- TCP/IP Model The TCP/IP model is a fundamental framework for computer networking. It stands for Transmission Control Protocol/Internet Protocol, which are the core protocols of the Internet. This model defines how data is transmitted over networks, ensuring reliable communication between devices. It consists of 13 min read
- User Datagram Protocol (UDP) User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection before data transfer. The UDP helps to establish low-late 10 min read
- Difference Between IPv4 and IPv6 The address through which any computer communicates with our computer is simply called an Internet Protocol Address or IP address. For example, if we want to load a web page or download something, we require the address to deliver that particular file or webpage. That address is called an IP Address 7 min read
- Difference Between Connection-oriented and Connection-less Services Two basic forms of networking communication are connection-oriented and connection-less services. In order to provide dependable communication, connection-oriented services create a dedicated connection before transferring data. On the other hand, connection-less services prioritize speed and effici 3 min read
- Socket Programming in Java This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection. There's a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) 5 min read
- java.net.ServerSocket Class in Java ServerSocket Class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). It is widely used so the ap 4 min read
- URL Class in Java with Examples URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it. Components of a URL A URL can have many forms. The most general however follows a th 4 min read
- Introduction to JDBC (Java Database Connectivity) JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language w 6 min read
- JDBC Drivers Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access any kind of tabular data, especially a relational database. JDBC Drivers uses JDBC APIs which was developed by Sun Microsystem, but now this is a p 4 min read
- Establishing JDBC Connection in Java Before Establishing JDBC Connection in Java (the front end i.e your Java Program and the back end i.e the database) we should learn what precisely a JDBC is and why it came into existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to ge 6 min read
- Types of Statements in JDBC The Statement interface in JDBC is used to create SQL statements in Java and execute queries with the database. There are different types of statements used in JDBC: Create StatementPrepared StatementCallable Statement1. Create a Statement: A Statement object is used for general-purpose access to d 6 min read
Java Memory Allocation
- Java Memory Management This article will focus on Java memory management, how the heap works, reference types, garbage collection, and also related concepts. Why Learn Java Memory Management? We all know that Java itself manages the memory and needs no explicit intervention of the programmer. Garbage collector itself ensu 6 min read
- How are Java objects stored in memory? In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only de 3 min read
- Stack vs Heap Memory Allocation Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program. Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of m 7 min read
- Java Virtual Machine (JVM) Stack Area For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may b 4 min read
- How many types of memory areas are allocated by JVM? JVM (Java Virtual Machine) is an abstract machine, In other words, it is a program/software which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actuall 3 min read
- Garbage Collection in Java Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedica 9 min read
- Types of JVM Garbage Collectors in Java with implementation details prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To 5 min read
- Memory leaks in Java In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C, Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there 1 min read
- Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per 15+ min read
- Java Multiple Choice Questions Java is a widely used high-level, general-purpose, object-oriented programming language and platform that was developed by James Gosling in 1982. Java Supports WORA(Write Once, Run Anywhere) also, it defined as 7th most popular programming language in the world. Java language is a high-level, multi- 3 min read
Java Practice Problems
- Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs. Java is one of the most popular programming languages today because of it 9 min read
- Java Exercises - Basic to Advanced Java Practice Programs with Solutions Looking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers 8 min read
- Java Quiz | Level Up Your Java Skills The best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi 4 min read
Java Projects
- Number guessing game in Java The task is to write a Java program in which a user will get K trials to guess a randomly generated number. Below are the rules of the game: If the guessed number is bigger than the actual number, the program will respond with the message that the guessed number is higher than the actual number.If t 3 min read
- Mini Banking Application in Java In any Bank Transaction, there are several parties involved to process transaction like a merchant, bank, receiver, etc. so there are several numbers reasons that transaction may get failed, declined, so to handle a transaction in Java, there is a JDBC (Java Database Connectivity) which provides us 7 min read
- Java program to convert Currency using AWT Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. 4 min read
- Tic-Tac-Toe Game in Java In the Tic-Tac-Toe game, you will see the approach of the game is implemented. In this game, two players will be played and you have one print board on the screen where from 1 to 9 number will be displayed or you can say it box number. Now, you have to choose X or O for the specific box number. For 6 min read
- Design Snake Game Let us see how to design a basic Snake Game that provides the following functionalities: Snake can move in a given direction and when it eats the food, the length of snake increases. When the snake crosses itself, the game will be over. Food will be generated at a given interval.Asked In: Amazon, Mi 9 min read
- Memory Game in Java The Memory Game is a game where the player has to flip over pairs of cards with the same symbol. We create two arrays to represent the game board: board and flipped. The board is an array of strings that represents the state of the game board at any given time.When a player flips a card, we replace 3 min read
- How to Implement a Simple Chat Application Using Sockets in Java? In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment). Java sockets can be connection-oriented or connection-less. In Java, we 4 min read
- Image Processing in Java - Face Detection Prerequisites: Image Processing in Java - Read and WriteImage Processing In Java - Get and Set PixelsImage Processing in Java - Colored Image to Grayscale Image ConversionImage Processing in Java - Colored Image to Negative Image ConversionImage Processing in Java - Colored to Red Green Blue Image C 3 min read
- Design Media Sharing Social Networking System PURPOSE OF MEDIA SOCIAL NETWORKING SERVICE SYSTEMThis system will allow users to share photos and videos with other users. Additionally, users can follow other users based on follow request and they can see other user's photos and videos. In this system, you can search users and see their profile if 14 min read
- Java Swing | Create a simple text editor To create a simple text editor in Java Swing we will use a JTextArea, a JMenuBar and add JMenu to it and we will add JMenuItems. All the menu items will have actionListener to detect any action.There will be a menu bar and it will contain two menus and a button: File menuopen: this menuitem is used 6 min read
- java-stream
IMAGES
VIDEO
COMMENTS
Java 9 introduces a few notable improvements to the Stream API that make working with streams even more expressive and efficient. In this section, we’ll cover the takeWhile() , dropWhile() , iterate() , and ofNullable() methods, exploring how they simplify various operations compared to Java 8.
In general, you don't assign values from within the stream to a variable; you extract a result from the stream (like the last VanTire instance). Do you want the very last element from the loop only? Since that is what your original loop is doing. If not, you should break; upon the first match.
Practicing hands-on exercises is a quick way to master a new skill. In this article, you will go through 15 exercises and cover a wide range of scenarios so as to gear you up the skill in Java Stream API. The exercises are based on a data model — customer, order and product.
Java Stream Creation is one of the most basic steps before considering the functionalities of the Java Stream. Below is the syntax given for declaring Java Stream. Streams in Java make data processing more efficient by supporting functional-style operations.
Here’s a deeper dive into the different ways you can create streams: 1. From Collections: Most collection classes like List, Set, and Map offer a convenient stream() method. This method returns...
Since Java 8, Stream can be defined as a sequence of elements from a source, such as collection or array. Learn about stream api with examples.
This functionality—java.util.stream—supports functional-style operations on streams of elements. This tutorial will guide you through the core concepts and new features, starting with basic stream operations and progressing to more advanced topics.
We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight.
Java SE 8 introduces three primitive specialized stream interfaces to tackle this issue—IntStream, DoubleStream, and LongStream—that respectively specialize the elements of a stream to be int, double, and long.
This Java 8 Stream Tutorial will cover all the basic to advanced concepts of Java 8 stream like Java 8 filter and collect operations, and real-life examples of Java 8 streams. Prerequisites for Java Stream