IntSummaryStatistics

IntSummaryStatistics provides different statistical data like max, min, average. This class is desinged to work with Java streams but can work with with out streams also.

Example

Following class shows an example of IntSummaryStatistics used with stream. It is used to print interesting information like max, min, average, sum and count. And then the accept method is used to add a new integer to the previous data passed as the numStream.
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
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

IntSummaryStatistics defined in java.util package and available since java 8 provides a way to calculate statistical information. It works with and with out stream.

Extract content of .war file

A WAR file (Web Application Resource or Web application Archive) is a file used to distribute a collection of files and folders associated with web application. Sometimes we want to look inside the war file to know what files or folders are inside the war file. Jar -xvf jar with option -xvf will extract the content of the war file. Following command will extract the content of blogapp.war file into the current directory

jar -xvf blogapp.war

To extract the content of war file type the above command. For instance for a war file blogapp.war we can use the command jar -xvf.
A generic square placeholder image with rounded corners in a figure.
Content of the blogapp.war file

Conclusion

jar -xvf can be used to extract the content of jar file. This command will work in any platform with installed java.

HashMap computeIfPresent() method in Java with Examples

The computeIfPresent(Key, BiFunction) method of HashMap class is used to update value in a key-value pair in the map. If key does not exist then it does not do any thing.

Syntax

undefined
V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) 

Example

Following is an example of computeIfAbsent invocation and its results.
ComputeIfAbsentExample
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);
	};
}
Output of above program.
Original Map
Watch -> 1501
Sunglass -> 105

After calling computeIfAbsent Map
Watch -> 3002
Sunglass -> 105

Summary

computeIfPresent helps in writing more compact code and also make code more readable.

HashMap computeIfAbsent() method in Java with Examples

The computeIfAbsent(Key, Function) method of HashMap class is used to enter a new key-value pair to map if the key does not exist. If key exists then it does not do any thing.

Syntax

undefined
public V computeIfAbsent(K key, Function<? super K, ? extends V> remappingFunction)

Example

Following is an example of computeIfAbsent invocation and its results.
ComputeIfAbsentExample
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);
	};
}
Output of above program.
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

computeIfAbsent helps in writing more compact code and also make code more readable.

Remove all entries in map by value

Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map by map values.

Using removeAll

removeAll() takes one argument a collection. And entries matching the passed collection will be removed from the original map
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);
});
Output of above program.
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

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);
});
Output of above program.
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

Java Map is a data structure that holds key->value pairs. In this article we will see how to delete all entries in the map in java easily and efficetively.

Method clear()

clear() method is method that does not return any thing (void return type) and is part of the Map interface. Each implementation subclasses provides an implementation. clear () methods deleted all entries and turn them map into empty map.
Clear method
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);
		});
	}
Output of above program.
Original Map
1 -> one
2 -> two
3 -> three
4 -> four
5 -> five
6 -> five

After classing clear() Map
empty

Summary

For removing all the entries from java map, clear() method is the best option. Also please note that the clear() method is implemented in each of its implementation classes like, HashMap, TreeMap, LinkedHashMap etc.

When to use Java BigInteger

Java BigInteger class is used to perform arithmetic operation or holding Numbers large enough that Integer cannot hold. In fact BigInteger does not have any limit on the numerical value that it can represent.

java.math.BigInteger

Integer Max and Min value

In Java Integer can hold between 2147483647 and -2147483648. This is denoted by Integer.MAX_VALUE and Integer.MIN_VALUE

Print Value of Integer Max and Min

Print max and min value
System.out.println(Integer.MAX_VALUE); //2147483647
System.out.println(Integer.MIN_VALUE);  //-2147483648
When we have numbers that cannot fit in the Integer range we can use BigInteger class. Also this Class provides a lot of methods to carry out different mathematical operations such as add, subtract, divide, multiply and many more
BigInteger Example
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);

Generate random number

Following java code will generate a random number between a given range. For instance if we want to generate a random number between 80, 100 we can use the following codes. In java to generate random number we have two options, using class Math or Random. We will see both examples

Using Class java.lang.Math

Math.random() generates a fraction(double) number between 0.0 and 1.0. We then add the lower bound to the product of (upperbound-lowerbound)*random_between0_1.
GenerateRandom1
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

GenerateRandom2
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

GenerateRandomNumber
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

Go to Terminal and execute following command (java --list-modules). It will list all the modules available in the JDK.
Terminal
$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
As we can see in the above command output, we have around 70 modules. All JDK Modules starts with "jdk.*" All Java SE Specifications Modules starts with "java.*"

What is package-info.java used for in Java

package-info.java is a special file which is used for generating package level documentations as well as keeping all package level annotations. For each package we can have one package-info file.
Here will see two different examples of package-info.java.

Package Documentation

For instance in a project, I have the following package-info.java for package javaexp.corejava.collection.
package-info.java
/**
 * Tutorials and Samples form Java  Collection framework.
 */

package javaexp.corejava.collection;
If we see the generated Javadocs we will notice the package level comments as well.





Package Level Annotation

We have the following entry, to mark the whole package deprecated.
package-info.java
@java.lang.Deprecated
package javaexp.corejava.oldcollection;
If we see the generated Javadoc we will see the package is marked as deprecated.



Summary

All though package-info.java is not must for java project, but it do add a lot of value specially if the code base is large and we want to generate package level documentations or say apply Annotations to all the classes in the packge.