Other classes similar to OptionalInt
are OptionalDouble
, OptionalLong
, and Optional
.
These help us eliminate exceptions that occur due to the absence of a value at runtime.
The key is to first check if the Optional contains a value before trying to retrieve it.
Table of Content
Java OptionalInt example
OptionalInt
allows us to create an object which may or may not contain an int value.
If a value is present, isPresent()
will return true and getAsInt()
will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse()
.
OptionalIntExample
In this example, we return an OptionalInt
from a Stream created from an integer array and finally return a value using the reduce()
method.
If the value is present, then only we print it using getAsInt()
.
package javaexp.blogspot.stream;
import java.util.Arrays;
import java.util.OptionalInt;
public class OptionalIntExample {
public static void main(String[] args) {
int iarray[] = {9, 10, 11, 12, 15, 15, 25};
OptionalInt result = Arrays.stream(iarray)
.reduce((left, right) -> left);
if (result.isPresent()) {
System.out.println("First element of Array: " + result.getAsInt());
}
}
}
Summary
OptionalInt
and other respective Optional classes help protect against
NullPointerException
when trying to retrieve values from potentially null objects.
They provide a safer way to work with values that may or may not be present.
IntSummaryStatistics
Example
public class IntSummaryStatisticsExample {
public static void main(String[] args) {
Stream<Integer> numStream = Stream.of(1, 2, 3, 4, 5);
IntSummaryStatistics summary = numStream.mapToInt(p-> p).summaryStatistics();
System.out.println("Max From the Data is " + summary.getMax());
System.out.println("Min From the Data is " + summary.getMin());
System.out.println("Average From the Data is " + summary.getAverage());
System.out.println("Sum From the Data is " + summary.getSum());
System.out.println("Count From the Data is " + summary.getCount());
//Add a new number to the stream
System.out.println("\n");
summary.accept(10);
System.out.println("Max From the Data is " + summary.getMax());
System.out.println("Min From the Data is " + summary.getMin());
System.out.println("Average From the Data is " + summary.getAverage());
System.out.println("Sum From the Data is " + summary.getSum());
System.out.println("Count From the Data is " + summary.getCount());
}
}
IntSummaryStatistics Example
Max From the Data is 5
Min From the Data is 1
Average From the Data is 3.0
Sum From the Data is 15
Count From the Data is 5
Adding number 10 to the data
Max From the Data is 10
Min From the Data is 1
Average From the Data is 4.166666666666667
Sum From the Data is 25
Count From the Data is 6
Conclusion
Extract content of .war file
jar -xvf blogapp.war

Conclusion
HashMap computeIfPresent() method in Java with Examples
Syntax
V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Example
package corejava.map;
import java.util.HashMap;
import java.util.Map;
public class ComputeIfPresentExample {
public static void main (String argv[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Sunglass", 105);
map.put("Watch", 1501);
newline("Original Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
map.computeIfPresent("Watch", (k,v) -> {return v + v;});
newline("After calling computeIfAbsent Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
}
static void newline(String s) {
System.out.println("\n" + s);
};
}
Original Map Watch -> 1501 Sunglass -> 105 After calling computeIfAbsent Map Watch -> 3002 Sunglass -> 105
Summary
HashMap computeIfAbsent() method in Java with Examples
Syntax
public V computeIfAbsent(K key, Function<? super K, ? extends V> remappingFunction)
Example
package corejava.map;
import java.util.HashMap;
import java.util.Map;
public class ComputeIfAbsentExample {
public static void main (String argv[]) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
newline("Original Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
map.computeIfAbsent(6, k-> { return "six";});
map.computeIfAbsent(7, k -> "seven");
newline("After calling computeIfAbsent Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
}
static void newline(String s) {
System.out.println("\n" + s);
};
}
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five After calling computeIfAbsent Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> six 7 -> seven
Summary
Remove all entries in map by value
Using removeAll
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
map.values().removeAll(Collections.singleton("five"));
newline("After removing values = five");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five 7 -> five After removing values = five 1 -> one 2 -> two 3 -> three 4 -> four
Using removeIf
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
//remove entries where value = five
map.values().removeIf("five"::equals);
newline("After removing values = five");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five 7 -> five After removing values = five 1 -> one 2 -> two 3 -> three 4 -> four
Remove all entries from java map
Method clear()
static void clearALLItemsInMap() {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
map.forEach( (a,b) -> {
System.out.println( a + " -> " + b);
});
//clear the map
map.clear();
newline("After classing clear() Map");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
}
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five After classing clear() Map empty
Summary
When to User BigInteger in Java
When to use Java BigInteger
java.math.BigInteger
Integer Max and Min value
Print Value of Integer Max and Min
System.out.println(Integer.MAX_VALUE); //2147483647
System.out.println(Integer.MIN_VALUE); //-2147483648
BigInteger a = BigInteger.valueOf(15);
BigInteger b = BigInteger.ONE;
BigInteger result = a.add(b);
System.out.println("Addition of a,b = " + result);
result = a.subtract(b);
System.out.println("Subtration of a,b = " + result);
result = a.divide(b);
System.out.println("Division of a,b = " + result);
result = a.multiply(b);
System.out.println("Multipllication of a,b = " + result);
How to generate Radom Integer in Java between two numbers.
Generate random number
Using Class java.lang.Math
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Using Class java.util.Random
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Full Example
import java.util.Random;
public class GenerateRandomNumber {
public static void main(String[] args) {
System.out.println(GenerateRandomNumber.generateRandomInteger(35, 40));
System.out.println(GenerateRandomNumber.generateRandomIntegerII(35, 40));
}
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
}
JDK Module listing
$java --list-modules java.base@18.0.1.1 java.compiler@18.0.1.1 java.datatransfer@18.0.1.1 java.desktop@18.0.1.1 java.instrument@18.0.1.1 java.logging@18.0.1.1 java.management@18.0.1.1 java.management.rmi@18.0.1.1 java.naming@18.0.1.1 java.net.http@18.0.1.1 java.prefs@18.0.1.1 java.rmi@18.0.1.1 java.scripting@18.0.1.1 java.se@18.0.1.1 java.security.jgss@18.0.1.1 java.security.sasl@18.0.1.1 java.smartcardio@18.0.1.1 java.sql@18.0.1.1 java.sql.rowset@18.0.1.1 java.transaction.xa@18.0.1.1 java.xml@18.0.1.1 java.xml.crypto@18.0.1.1 jdk.accessibility@18.0.1.1 jdk.attach@18.0.1.1 jdk.charsets@18.0.1.1 jdk.compiler@18.0.1.1 jdk.crypto.cryptoki@18.0.1.1 jdk.crypto.ec@18.0.1.1 jdk.dynalink@18.0.1.1 jdk.editpad@18.0.1.1 jdk.hotspot.agent@18.0.1.1 jdk.httpserver@18.0.1.1 jdk.incubator.foreign@18.0.1.1 jdk.incubator.vector@18.0.1.1 jdk.internal.ed@18.0.1.1 jdk.internal.jvmstat@18.0.1.1 jdk.internal.le@18.0.1.1 jdk.internal.opt@18.0.1.1 jdk.internal.vm.ci@18.0.1.1 jdk.internal.vm.compiler@18.0.1.1 jdk.internal.vm.compiler.management@18.0.1.1 jdk.jartool@18.0.1.1 jdk.javadoc@18.0.1.1 jdk.jcmd@18.0.1.1 jdk.jconsole@18.0.1.1 jdk.jdeps@18.0.1.1 jdk.jdi@18.0.1.1 jdk.jdwp.agent@18.0.1.1 jdk.jfr@18.0.1.1 jdk.jlink@18.0.1.1 jdk.jpackage@18.0.1.1 jdk.jshell@18.0.1.1 jdk.jsobject@18.0.1.1 jdk.jstatd@18.0.1.1 jdk.localedata@18.0.1.1 jdk.management@18.0.1.1 jdk.management.agent@18.0.1.1 jdk.management.jfr@18.0.1.1 jdk.naming.dns@18.0.1.1 jdk.naming.rmi@18.0.1.1 jdk.net@18.0.1.1 jdk.nio.mapmode@18.0.1.1 jdk.random@18.0.1.1 jdk.sctp@18.0.1.1 jdk.security.auth@18.0.1.1 jdk.security.jgss@18.0.1.1 jdk.unsupported@18.0.1.1 jdk.unsupported.desktop@18.0.1.1 jdk.xml.dom@18.0.1.1 jdk.zipfs@18.0.1.1
What is package-info.java used for in Java
Package Documentation
/**
* Tutorials and Samples form Java Collection framework.
*/
package javaexp.corejava.collection;
Package Level Annotation
@java.lang.Deprecated
package javaexp.corejava.oldcollection;
Summary
What is @Deprecated annotation in Java
Java @Deprecated Annotation
Where @Deprecated can be used
- Method can be marked @Deprecated.
- Class can be marked with @Deprecated.
- Package can be also marked deprecated with @Deprecated.
Effect of marking with @Deprecated
Example
/**
* Sample Calculator which can add two numbers
*
*/
public class OldCalculator {
/**
* Add two number and return the value as Number
*
* @param a : First number
* @param b : Second number
* @return result of addition as Number
* @see Number
*/
public Number add(Number a, Number b) {
return a.doubleValue() + b.doubleValue();
}
@Deprecated(forRemoval = false, since = "1.1")
public Number add(CalParameter a, CalParameter b) {
return a.val.doubleValue() + b.val.doubleValue();
}
}
@Deprecated
class CalParameter {
Integer val;
}
Documentation of @Deprecated
When to use @Deprecated
Create Java project using maven
- Java 18.0.1.1 2022-04-22
- Apache Maven 4.0.0-alpha-3
- OS: MacOS Monterey (M1)
- Eclipse IDE
Create project
mvn archetype:generate -DgroupId=com.project -DartifactId=java-module-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
$ mvn archetype:generate -DgroupId=com.project -DartifactId=java-module-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] -----------------------------------------< org.apache.maven:standalone-pom >----------------------------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] -------------------------------------------------------[ pom ]------------------------------------------------------- [INFO] [INFO] --- archetype:3.2.1:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Batch mode [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: basedir, Value: /Users/sbhome [INFO] Parameter: package, Value: com.project [INFO] Parameter: groupId, Value: com.project [INFO] Parameter: artifactId, Value: java-module-project [INFO] Parameter: packageName, Value: com.project [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: /Users/sbhome/java-module-project [INFO] --------------------------------------------------------------------------------------------------------------------- [INFO] BUILD SUCCESS [INFO] --------------------------------------------------------------------------------------------------------------------- [INFO] Total time: 6.667 s [INFO] Finished at: 2023-02-07T22:46:00-08:00 [INFO] --------------------------------------------------------------------------------------------------------------------- Terminal:: $
cd java-module-project
Create Eclipse Project
mvn eclipse:eclipse
[INFO] Scanning for projects... [INFO] [INFO] -----------------------------------------< com.project:java-module-project >----------------------------------------- [INFO] Building java-module-project 1.0-SNAPSHOT [INFO] from pom.xml [INFO] -------------------------------------------------------[ jar ]------------------------------------------------------- [INFO] [INFO] --- eclipse:2.10:eclipse (default-cli) @ java-module-project --- [WARNING] The POM for org.apache.maven.wagon:wagon-http-lightweight:jar:1.0-beta-6 is invalid, transitive dependencies (if any) will not be available, enable verbose output (-X) for more details [WARNING] The POM for org.apache.maven.wagon:wagon-http:jar:1.0-beta-6 is invalid, transitive dependencies (if any) will not be available, enable verbose output (-X) for more details [WARNING] The POM for org.apache.maven.wagon:wagon-webdav-jackrabbit:jar:1.0-beta-6 is invalid, transitive dependencies (if any) will not be available, enable verbose output (-X) for more details [WARNING] The POM for org.apache.maven.wagon:wagon-http-lightweight:jar:1.0-beta-2 is invalid, transitive dependencies (if any) will not be available, enable verbose output (-X) for more details [INFO] Using Eclipse Workspace: null [INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER [INFO] Not writing settings - defaults suffice [INFO] Wrote Eclipse project for "java-module-project" to /Users/sbhome/java-module-project. [INFO] [INFO] --------------------------------------------------------------------------------------------------------------------- [INFO] BUILD SUCCESS [INFO] --------------------------------------------------------------------------------------------------------------------- [INFO] Total time: 0.494 s [INFO] Finished at: 2023-02-07T22:51:03-08:00 [INFO] ---------------------------------------------------------------------------------------------------------------------
Import Project in Eclipse
Project in Eclipse
POM file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.project</groupId>
<artifactId>java-module-project</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>java-module-project</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Build Project
mvn install
[INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.project.AppTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s - in com.project.AppTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] [INFO] --- jar:3.2.0:jar (default-jar) @ java-module-project --- [INFO] Building jar: java-module-project-1.0-SNAPSHOT.jar [INFO] [INFO] --- install:3.0.0-M1:install (default-install) @ java-module-project --- [INFO] [INFO] --------------------------------------------------------------------------------------------------------------------- [INFO] BUILD SUCCESS
Java logical operator short circuit with example
Java logical operator short circuiting
private static boolean appleIsFruit() {
System.out.println("calling apple ");
return true;
}
private static boolean bananaIsFruit() {
System.out.println("calling banana ");
return true;
}
private static boolean cloudIsfruit() {
System.out.println("calling cloud ");
return false;
}
System.out.println("\n\napple | banana");
if (appleIsFruit() | bananaIsFruit()) {
System.out.println("inside apple | banana");
}
System.out.println("\n\ncloud & apple");
if (cloudIsfruit() & appleIsFruit()) {
System.out.println("inside cloud & apple");
}
apple | banana calling apple calling banana inside apple | banana cloud & apple calling cloud calling apple
System.out.println("apple || banana");
if (appleIsFruit() || bananaIsFruit()) {
System.out.println("inside apple || banana");
}
System.out.println("\n\ncloud && apple");
if (cloudIsfruit() && appleIsFruit()) {
System.out.println("inside cloud && apple");
}
apple || banana calling apple inside apple || banana cloud && apple calling cloud
Summary
How to iterate Java Map
Map<Integer, String> map = new HashMap<>();
map.put(1,"Argentina");
map.put(2,"France");
map.put(3,"Brazil");
map.put(4,"Germany");
//EntrySet Iterator
System.out.println("\nEntrySet foreach");
Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> keyVal = it.next();
System.out.println(keyVal.getKey() + " " + keyVal.getValue());
}
//EntrySet and foreach
System.out.println("\nEntrySet foreach");
Set<Entry<Integer, String>> entrySet = map.entrySet();
entrySet.forEach((e-> { System.out.println(e.getKey() + " " + e.getValue());}));
//Keyset Iterator
System.out.println("\nKeyset Iterator");
Iterator<Integer> kit = map.keySet().iterator();
while(kit.hasNext()) {
Integer key = kit.next();
System.out.println(key + " " + map.get(key));
}
//Keyset For loop
System.out.println("\nKeyset For loop");
for (Integer key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
//map foreach (Java 8 Lambda)
System.out.println("\nUsing Map.foreach (Java 8 Lambda");
map.forEach((key,value)-> {System.out.println(key + " " + value);});
Summary
Java LinkedHashMap.removeEldestEntry method example
When to use LinkedHashMap.removeEldestEntry
method
removeEldestEntry
method exists only on subclasses of LinkedHashMap
.
How it works
removeEldestEntry
is always invoked after an element is inserted.- Based on the method’s return value:
- Returns true: The oldest entry is removed.
- Always returns true: The map continuously removes entries (will become empty).
- Returns false: Nothing is removed; behaves like a normal LinkedHashMap.
After every put
or putAll
insertion, the eldest element may be removed depending on the logic. The JavaDoc provides a clear example of this usage.
Example: removeEldestEntry
import java.util.LinkedHashMap;
import java.util.Map;
public class MapRemoveEntry {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
return size() > 4;
}
};
map.put(0, "A");
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "E");
map.forEach((k, v) -> System.out.println("key = " + k + " value = " + v));
}
}
Output:
key = 2 value = C
key = 3 value = D
key = 4 value = E
Explanation: The method removeEldestEntry
returns true when the map size is greater than 4. This removes the oldest entry (key=0, value=A).
Summary
Using removeEldestEntry
, you can control when to remove the oldest entry from a map. This is particularly useful for implementing caches where you want to limit the number of stored items.
About sealed classes and interfaces
Defining sealed class
sealed Tesla
package java17.sealed;
public abstract sealed class Tesla permits Model3, ModelS, TeslaSUV{
public abstract Integer maxRange();
public String basePrice() {
return "25000 USD";
}
}
//Subclass 1
public final class Model3 extends Tesla {
@Override
public Integer maxRange() {
return 200;
}
}
//Subclass 2
public final class ModelS extends Tesla {
@Override
public Integer maxRange() {
return 400;
}
}
//Subclass3 (non-sealed)
public non-sealed class TeslaSUV extends Tesla {
@Override
public Integer maxRange() {
// TODO Auto-generated method stub
return null;
}
}
Style Two: Using member classes
package java17.sealed;
public sealed class BMWCars {
public final class BMW3 extends BMWCars implements ElectricVehicle{
}
public final class BMWI extends BMWCars implements Vehicle {
}
public non-sealed class BMWJV extends BMWCars implements Vehicle {
}
}
Rules for Defining Sealed Classes or Interfaces
Summary
Java record in details with example
package Java14;
public record AddressRecord(String street, String city, Integer zip, String state, String country) {
}
package Java14;
public class AddressRecordDemo {
public static void main (String arg[]) {
AddressRecord address1 = new AddressRecord("1044 Main Street", "Livermore", 94550, "CA", "USA");
System.out.println(address1.street());
System.out.println(address1.city());
System.out.println(address1.state());
}
}
- record can have Constructor.
- record can have only static fields.
- record cannot have instance field.
- record can implement Interfaces.
- We cannot extends record since implicitly it is final.
How to check if a Java object is final
How to check if a Java object is final
final class MyCustomClass {
}
Using java.lang.reflect.Modifier
import java.lang.reflect.Modifier;
public class JavaReflectionModifiers {
public static void main(String[] args) {
//prints 16
System.out.println(MyCustomClass.class.getModifiers());
//returns true
Modifier.isFinal(MyCustomClass.class.getModifiers());
}
}
final class MyCustomClass {
}
More Examples
package Java14;
import java.lang.reflect.Modifier;
public class JavaReflectionModifiers {
public static void main(String[] args) {
System.out.println(MyCustomClass.class.getModifiers());
//prints true
System.out.println(Modifier.isFinal(MyCustomClass.class.getModifiers()));
//prints true
System.out.println(Modifier.isFinal(String.class.getModifiers()));
//prints false
System.out.println(Modifier.isFinal(Number.class.getModifiers()));
}
}
final class MyCustomClass {
}
Can Java record be extended?
record MobilePhone(String brand, String modelName, Number osVersion, boolean canFlip) {
}
package Java14;
import java.lang.reflect.Modifier;
public class RecordFinalTest {
public static void main(String[] args) {
MobilePhone phone1 = new MobilePhone("Samsung", "Galaxy1", 1, false);
//false
System.out.println(Modifier.isFinal(phone1.getClass().getModifiers()));
//false
System.out.println(Modifier.isFinal(MobilePhone.class.getModifiers()));
}
}