Java OptionalInt example

OptionalInt allows us to create an object which may or may not contain a 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().
Other classes similar to OptionalInt are OptionalFloat, OptionalDouble, Optional. These can help us eliminate exceptions that occur due to the absence of a value at runtime. Basically we need to first check if the Optional is carrying any value then only try to get value.
In this example we are returning an OptionalInt from Stream created from integer array and finally returning the sum using reduce method. If the Value is present then only we are trying to pring the value by calling result.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("Sum of Array " + result.getAsInt());
    }
    
  }

}

Summary

OptionalInt and other respective Optional classes helping in protecting from Nullpointer exception when we try to get value (say integer value) from and Integer object which is null.

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.

Default Method in Java

The default method in Interfaces was introduced in Java 8. It allows the interface to implement a method in the interface which is inherited by implementing classes.

What are default methods?

Before Java 8 methods in the interface could have only public and abstract modifiers for methods and public, static and for fields public and static or blank (blank means public and static field).

Java 5

Following are two interfaces in Java 5, the first one is valid and the second one is not.
Valid Interface in Java 5
interface Java5Interface {
	public static int four = 4;
	int five = 5; // implicitly public static

	public abstract void welcome();
	public void sayHi();
	void bye();
}
Invalid Interface in Java 5
interface Java5Invalid {
	private int six = 6;            //illegal only public static and final is permitted
	private void cleanuup(); // illegal only public and abstract is permitted
}
As you can see for fields only public, static, and final modifiers are allowed. If nothing is mentioned then also all fields in Java 5 is public static and final implicitly. For methods, we can have only public and abstract as modifiers.

Java 8 and onwards

Starting Java 8 methods in the interface can have the following modifiers public, private, abstract, default, static, strictfp. Nothing changes for fields, fields can still have public, static, final modifiers. In the following example, we have a Greetings Interface with two default methods greet and openDoor respectively. This interface also has one static method lockdoor.
Interface Greetings in Java 8
interface Greetings {
	
	public default void greet() {
		openDoor();
		sayHi();
		sayBye();
		closeDoor();
	}
	
	default void openDoor() {
		//open the door
	}
	
	void sayHi();
	
	void sayBye();
	
	private void closeDoor() {
		lockDoor();
	}

	static void lockDoor() {
		//lock door implementation
	}
}
The benefit of having a default method is that now the interface can provide a default implementation of methods through the default modifier. For instance, the interface Greetings provided a default implementation for method greet(). Also the later we can add more default, private or static methods to the Interface without breaking binary compatibility meaning implementing classes don't need to do any modification to be able to compile and run successfully.
Importat Points
  • default methods are public.
  • default methods are inherited by implementation classes.
  • default methods can be overridden by implementation classes.
  • a default method can add more functionality to the Interface without breaking binary compatibility.
  • static methods are also allowed which are Interface level methods and cannot be overridden by subclasses.
  • Java 8 methods can have public, private, abstract, default, static, and strictfp.

References

Java Files walk examples

Java File.walk method is available in java 8. It is very useful to traverse the the content of a file tree. Walks goes in a depth first fashion and return a Stream object. We can then work with the stream to get the required result. Like we can filter only directories, find files matching some name etc. This article covers three example of using File.walk to list all the directories, files and both.

List all the folders

List all the directories/folders inside the location specified by path.
public List getFolders(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isDirectory).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());
    result.forEach(System.out::println);
    walk.close();
    return result;
  }

List all files

Similar to above method, but the filter condition is different. Here we are filtering only regular files with Files::isRegularFile.
public List getFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.filter(Files::isRegularFile).map(x -> x.getFileName().toString())
        .collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }

Files and Directories

Following method will list all the directories: with files inside it. It is similar to linux command ls *.
public List getFoldersAndFiles(String path) throws IOException {
    Stream walk = Files.walk(Paths.get(path));
    List result = walk.map(x -> {
      if (Files.isDirectory(x)) {
        return x.getFileName().toString() + ":";
      } else
        return x.getFileName().toString();
    }).collect(Collectors.toList());

    result.forEach(System.out::println);
    walk.close();

    return result;
  }

References