Skip to main content


Showing posts from November, 2021

Java Stream boxed() With Examples

The boxed() method in Java Stream is used to wrap the primitive value (int, long or double) to its respective wrapper class object. There are primitive specializations of Stream named IntStream, LongStream and DoubleStream each of these interfaces have a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer, Long or Double respectively. Note that boxed() is an intermediate operation . boxed stream Java examples Let’s see few examples how to box a primitive value into its wrapper class using boxed() method. 1. boxed() in IntStream which is used to get a Stream consisting of the elements of this stream, each boxed to an Integer. import java.util.List; import; import; import; public class BoxedIntStream { public static void main(String[] args) { Stream<Integer> wrappedInts = IntStream.of(1, 2, 3, 4, 5).boxed(); List<Integer>

Java Stream concat() With Examples

If you want to merge two streams you can use concat() method in Java Stream API. Syntax of concat() method concat(Stream<? extends T> a, Stream<? extends T> b) Here a represents the first stream and b represents the second stream. Method returns a stream consisting all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. concat() method Java examples 1. Using concat() method to merge streams of Strings. public class ConcatDemo { public static void main(String[] args) { Stream<String> stream1 = Stream.of("A", "B", "C"); Stream<String> stream2 = Stream.of("D", "E", "F"); Stream<String> mergedStream = Stream.concat(stream1, stream2); mergedStream.forEach(System.out::println); } } Output A B C D E F 2. Usin

Java HashMap compute() With Examples

The Java HashMap compute() method is used to compute a new value for the specified key. Syntax of compute() method compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) The parameters are- key - Key with which the computed value has to be mapped. remappingFunction - It is an expression of type BiFunction functional interface used to compute a value. Method returns a new value associated with the specified key or null if there is no new values. If the remapping function returns null, the mapping is removed (or remains absent if initially absent). compute() method Java examples 1. In this example a new value is computed for the specified key. For the example a HashMap is created with product name as key and price as value. Then compute() is used to change the price (value) for the specified key. import java.util.HashMap; import java.util.Map; public class MapComputeDemo { public static void main(String[] args) { Map<String, Do

Map#putIfAbsent() in Java With Examples

In this tutorial you will see how to use putIfAbsent() method in Java HashMap . The putIfAbsent() method inserts the specified value if the passed key is not already present in the HashMap or the key is null. Using this method gives you an option to check if key is already present or not, before associating a value with the key. What this method does in a single statement can be explained as- V v = map.get(key); if (v == null) v = map.put(key, value); return v; Syntax of putIfAbsent() method V putIfAbsent(K key, V value) Here the parameters are- key - key with which the specified value is to be associated value - value to be associated with the specified key This method returns the previous value if key is already associated with a value or null if there was no existing mapping for the key. Method also returns null if key was previously inserted as null in the HashMap. Note that the default implementation of the putIfAbsent() method in the Map interface makes

Java Stream count() With Examples

In Java Stream API there is a count() method that returns the count of elements in the stream. In this tutorial you’ll learn about count() method with the help of some examples. Java Stream count() method Syntax of the count() method is as follows- long count() count method is a special case of a reduction operation as it takes a sequence of input elements and combines them into a single summary result. This method is a terminal operation meaning it produces a result and stream pipeline is considered consumed, and can no longer be used after count operation. count() method Java examples 1. Using count() to get the number of elements in a List by using list as a Stream source. import java.util.Arrays; import java.util.List; public class CountDemo { public static void main(String[] args) { List<Integer> numList = Arrays.asList(3, 5, 4, 12, 16, 0, 7, 6); long result =; System.out.println("Number of elements- " + result)

Java Stream – Convert a Stream to Map

In this tutorial you’ll see how to convert a Stream to Map using collector method and utility methods like toMap() and groupingBy() of Collectors class in Java Stream API . Syntax of toMap() method is as given below- toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) This method returns a Collector that accumulates elements into a Map. Both of the arguments passed to the method are of type Function which is a functional interface . Using these mapping functions keyMapper and valueMapper, keys and values of the resulting Map are calculated. 1. Using Collectors.toMap() method In the following example a list of students is collected to a Map where key is the student’s roll number and value is Student name. Student class used is- public class Student { private int rollNo; private String name; private String stream; private int marks; Student(int rollNo, String name, String stream, int marks){ this.rollNo

Java Stream peek() With Examples

In this tutorial we’ll see how to use Java Stream peek() method with the help of few examples. Syntax of peek() method in Java Stream API Stream<T> peek(Consumer<? super T> action) Argument passed to the peek method is of type Consumer functional interface which represents a non-interfering action to perform on the elements as they are consumed from the stream. Method returns a new Stream. peek() is an intermediate operation which means using peek() without any terminal operation will do nothing. Java 9 onward, if the number of elements in Stream source is known in advance then no source elements will be traversed and no intermediate operations like peek() will be evaluated. This is a performance optimization. peek() method exists mainly to support debugging, where you want to see the elements as they flow from one operation to another with in the Stream pipeline. Java Stream peek() examples 1. In this example peek() method is used to display the stream elem

Java Program to Find Factorial

In this post we’ll see a Java program to find the factorial of a number. Factorial of a non-negative integer n is product of all positive integers less than or equal to n. For example 5! = 5 X 4 X 3 X 2 X 1 = 120 Factorial program in Java Factorial program in Java can be written as both iterative as well as recursive solution. In this post both of the solutions are given. Factorial program using iteration In the following program user is asked to enter the number for which factorial has to be calculated. In iterative logic you can start a for loop with the entered number and decrease it by 1 in each iteration. What you need is the multiplication of all the numbers in the loop. import java.util.Scanner; public class Factorial { public static void main(String[] args) { // Input from user Scanner input = new Scanner(; System.out.println("Enter a number: "); int number = input.nextInt(); int factorial = 1; for(int i = number; i >

Exception Propagation in Java

In the execution of the method code, if an exception condition occurs, normal flow of the method is disrupted. In order to handle the exceptional condition an exception object is created and thrown. That exception may be handled in the method where that exception is thrown or it may be passed on to be handled by other methods in the caller stack. This process of going through the method call stack to look for an exception handler that can handle the thrown exception is known as exception propagation in Java . Table of contents Exception propagation in Java Exception Propagation flow Exception Propagation in Java with checked and unchecked exceptions Exception propagation Java example with unchecked exception Exception propagation Java example with checked exception Exception propagation in Java To reach to a certain method in the code, some other methods are called in between. This list of methods is known as the method call stack . When an exception o

Java String join() Method With Examples

In Java 8 join() method has been added to the Java String class that joins together the given strings using the specified delimiter. Read Also: Java StringJoiner Class With Method Examples Java String join() method There are two variants of the join() method- public static String join(CharSequence delimiter, CharSequence... elements) - This method returns a new String created by joining together the elements using the specified delimiter. public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) - Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String. Java String join() method examples 1. Joining 3 strings using space (" ") as delimiter and using colon ":" as delimiter. public class JoinStrings { public static void main(String[] args) { String str1 = "Java";

Java String split() Method

Java String split() method splits the string around matches of the given regular expression. The split() method returns string array which contains all the words computed by splitting this string around matches of the given regular expression. In Java String class there are two variants of split() method- String[] split(String regex, int limit) String[] split(String regex) Method parameters are- regex - The delimiting regular expression limit - The limit parameter controls the number of times the pattern is applied, it may have following three values. If limit > 0 then the pattern will be applied at most limit - 1 times. Returned String array's length will be no greater than limit, and the array's last entry will contain all input beyond the last matched delimiter. If limit = zero then the pattern will be applied as many times as possible, returned String array can have any length and trailing empty strings will be discarded. If limit < 0 then the p

Java String intern() Method

This post gives an insight into the Java String intern() method which is closely associated with the concept of "interning" strings in Java and maintaining a String pool in Java . String interning in Java In Java, string literals are "interned" so as to share unique instances. A pool of strings, initially empty, is maintained privately by the class String. For every string literal (String value enclosed in double quotes) JVM scans the String pool for any String having the same value, if found same reference is returned. So, new memory is not allocated for the same string, existing memory is used instead and the reference is shared. Let’s understand with an example. if two Strings are created as follows- String str1 = “Hello” String str2 = “Hello” Then the same memory is referenced by both the objects. intern method in String String literal are interned by default in Java but same is not true for the Strings created using new operator. For such String

Check if a String is Null or Empty in Java

To check if a String is null or empty in Java you can use one of the following options. Use isEmpty() method available Java 6 onward to check if the String is empty. Use StringUtils.isEmpty() method of the Apache Commons Lang. From Java 11 onward there is also isBlank() method to check if the String is empty or contains only white spaces. Check String empty or null using isEmpty() In order to check if String empty or null in Java you should first check whether the String is null or not then check if it is empty or not. If you use or condition (||) then second part is not evaluated if the first part itself is true, so you won’t be calling isEmpty() method on a null String if String itself is null. For example- if(str == null || str.isEmpty()) If String is null then first part of the condition itself evaluates to true and second part is not checked. public class StringEmpty { public static void main(String[] args) { String str1 = "A String"; St

Java String charAt() Method

If you want to get specific character of the String by index you can use charAt() method of the String class in Java . charAt() method char charAt(int index) - Returns the char value at the specified index. For a String of length n the passed index should be with in the range 0 to n-1. Method throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string. Java String charAt() method examples 1. Using charAt() to get the first and last characters of the String. public class StringCase { public static void main(String[] args) { String str = "Hello World"; // getting first character char firstChar = str.charAt(0); // getting last character char lastChar = str.charAt(str.length()-1); System.out.println("First character- " + firstChar); System.out.println("Last character- " + lastChar); } } Output First character- H Last character- d Since index starts at 0 so first char

Java String toLowerCase() And toUpperCase() Methods

In this post you’ll learn how to change case of the String in Java using toLowerCase() and toUpperCase() methods. toLowerCase() method in Java String String toLowerCase() - Used to convert all of the characters in this String to lower case. If no argument is passed then rules of the default locale is used, making it equivalent to calling toLowerCase(Locale.getDefault()). Note that this method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. String toLowerCase(Locale locale) - Converts all of the characters in this String to lower case using the rules of the given Locale. public class StringCase { public static void main(String[] args) { String str = "TEST String"; System.out.println("String converted in all lower case- " + str.toLowerCase()); } } Output String converted in all lower case- test string Note that the modified string is a new String object whi

Java String - substring() Method Example

If you have to get a part of the original String i.e. substring in Java then you can use substring() method of the Java String class . Java substring() method There are two variants of the substring() method- String substring(int beginIndex) - Returns a substring of this string where the substring begins with the character at the beginIndex and goes till the end of this string. Method throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object. String substring(int beginIndex, int endIndex) - Returns a string that is a substring of this string. The substring begins at the specified beginIndex and ends at index endIndex - 1. IndexOutOfBoundsException is thrown if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. For this variant of substring() method remember that- beginIndex- the beginning index, inclusive. endIndex- the ending index, exclusi