Search Java Code Snippets

  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.

#Java - Code Snippets for '#Java 8' - 23 code snippet(s) found

 Sample 1. Calculate square of a number using Lambda Expression

public interface Calc {
int square(int value);

public static void main(String[] args){
Calc calc = (int val) -> val * val;

   Like      Feedback     lambda Expression  java 8

 Sample 2. Write a Program that gets a set of numbers , filters out the non prime numbers , calculate the factorial of each prime number and then finds the average of all factorials using Lambda expressions

public class BuggyBread1 {
   public static void main(String args[]) {
      // Declare and Initialize the Collection
      Set<Integer> intSet = new HashSet<Integer>();

      // Add Elements

      double averageOfNonPrimeFactorials =>checkIfPrime(p)).collect(Collectors.averagingInt(p->calculateFactorial(p)));
      System.out.println(averageOfNonPrimeFactorials );
   static private boolean checkIfPrime(int num){
      for(int count=2;count < num;count++){
         if(num % count == 0){
            return false;
      return true;
   static private int calculateFactorial(int num){
      int factorial = 1;
      for(int count=num;count > 0;count--){
         factorial = factorial * count;
      return factorial;

   Like      Feedback     java 8  lambda expressions  lambda  filter  Collectors  factorial  prime number

 Sample 3. Interface Default Methods ( Base Class Definition has precedence over Interface Default Method if both are being extended and implemented and have common method definition )


public class HelloJava8Base {
public void defaultMethod() {
System.out.println("Default Method Base Class Implementation");


public interface DefaultMethodInterface {
default public void defaultMethod() {
System.out.println("Default Method Interface Implementation");


public class HelloJava8 extends HelloJava8Base implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface dmi = new HelloJava8();
dmi.defaultMethod(); // Prints "Default Method Base Class Implementation"

   Like      Feedback     interface default methods  java 8  interfaces

 Sample 4. Get the Calendar Type from the abstract chronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;
System.out.println(abstractChrono.getCalendarType()); // Will print buddhist

   Like      Feedback     AbstractChronology  java 8  AbstractChronology.getCalendarType

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
 Sample 5. Display Elements of a List using Java 8 Consumer

List myList = new ArrayList();


   Like      Feedback     Print elements of a list   java 8  consumer  foreach   list  arraylist  collections

 Sample 6. Interface Default Methods

public interface DefaultMethodInterface {
default public void defaultMethod(){

public interface DefaultMethodInterface2 {
default public void defaultMethod(){

public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();

public void defaultMethod(){

   Like      Feedback     interface default methods   interfaces  java 8

 Sample 7. ArrayList of Optional Integers

List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();

// Add Elements


   Like      Feedback     optional  java 8   list   arraylist   list of optional integers   arraylist of optional  java.util.Optional

 Sample 8. Get Date using ZonedDateTime and LocalDateTime

ZonedDateTime zonedDatetime = ZonedDateTime.of(201, 1, 31, 14, 35, 12, 123, ZoneId.of("UTC-11"));

LocalDateTime localDateTime = LocalDateTime.of(2015, 03, 10, 13, 36);

ZonedDateTime zonedDatetime2 ="merica/Chicago"));

ZonedDateTime zonedDatetime3 = ZonedDateTime.of(localDateTime, ZoneId.of("America/Chicago"));

   Like      Feedback     ZonedDateTime   LocalDateTime   ZonedDateTime.of  LocalDateTime.of  ZoneId  ZoneId.of  java.time.ZonedDateTime  java.time   java 8

 Sample 9. Internal Implementation of ChronoField

public enum ChronoField implements TemporalField {
NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999)),
NANO_OF_DAY("NanoOfDay", NANOS, DAYS, ValueRange.of(0, 86400L * 1000_000_000L - 1)),
MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, ValueRange.of(0, 999_999)),
MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, ValueRange.of(0, 86400L * 1000_000L - 1)),
MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, ValueRange.of(0, 999)),
MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, ValueRange.of(0, 86400L * 1000L - 1)),
SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second"),
SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, ValueRange.of(0, 86400L - 1)),
MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute"),
MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, ValueRange.of(0, (24 * 60) - 1)),
HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(0, 11)),
CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12)),
HOUR_OF_DAY("HourOfDay", HOURS, DAYS, ValueRange.of(0, 23), "hour"),
CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1, 24)),
AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0, 1), "dayperiod"),
DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1, 7), "weekday"),
ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7)),
ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7)),
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),
DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366)),
EPOCH_DAY("EpochDay", DAYS, FOREVER, ValueRange.of((long) (Year.MIN_VALUE * 365.25), (long) (Year.MAX_VALUE * 365.25))),
ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5)),
ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53)),
MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1, 12), "month"),
PROLEPTIC_MONTH("ProlepticMonth", MONTHS, FOREVER, ValueRange.of(Year.MIN_VALUE * 12L, Year.MAX_VALUE * 12L + 11)),
YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, ValueRange.of(1, Year.MAX_VALUE, Year.MAX_VALUE + 1)),
YEAR("Year", YEARS, FOREVER, ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), "year"),
ERA("Era", ERAS, FOREVER, ValueRange.of(0, 1), "era"),
OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, ValueRange.of(-18 * 3600, 18 * 3600));

private final String name;
private final TemporalUnit baseUnit;
private final TemporalUnit rangeUnit;
private final ValueRange range;
private final String displayNameKey;

private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) { = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = null;

private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
ValueRange range, String displayNameKey) { = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = displayNameKey;

public String getDisplayName(Locale locale) {
Objects.requireNonNull(locale, "locale");
if (displayNameKey == null) {
return name;

LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()
ResourceBundle rb = lr.getJavaTimeFormatData();
String key = "field." + displayNameKey;
return rb.containsKey(key) ? rb.getString(key) : name;

public TemporalUnit getBaseUnit() {
return baseUnit;

public TemporalUnit getRangeUnit() {
return rangeUnit;

public ValueRange range() {
return range;

public boolean isDateBased() {
return ordinal() >= DAY_OF_WEEK.ordinal() && ordinal() <= ERA.ordinal();

public boolean isTimeBased() {
return ordinal() < DAY_OF_WEEK.ordinal();

public long checkValidValue(long value) {
return range().checkValidValue(value, this);

public int checkValidIntValue(long value) {
return range().checkValidIntValue(value, this);

public boolean isSupportedBy(TemporalAccessor temporal) {
return temporal.isSupported(this);

public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
return temporal.range(this);

public long getFrom(TemporalAccessor temporal) {
return temporal.getLong(this);

public <R extends Temporal> R adjustInto(R temporal, long newValue) {
return (R) temporal.with(this, newValue);

public String toString() {
return name;


   Like      Feedback     chronofield  temporalfield  java 8  java.time.temporal.TemporalField

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
 Sample 10. Today's Date as per Hijrah Chronology

AbstractChronology abstractChrono = HijrahChronology.INSTANCE;

   Like      Feedback     Hijrah Date  Hijrah Calendar  Hijrah Chronology  HijrahChronology  java 8  HijrahChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow

 Sample 11. Today's Date as per Japanese Chronology

AbstractChronology abstractChrono = JapaneseChronology.INSTANCE;

   Like      Feedback     Japanese Chronology  JapaneseChronology  java 8  JapaneseChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow

 Sample 12. Todays Date as per Minguo Chronology

AbstractChronology abstractChrono = MinguoChronology.INSTANCE;

   Like      Feedback     Minguo Chronology  MinguoChronology  java 8  MinguoChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow

 Sample 13. Todays Date as per ThaiBuddhistChronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;


   Like      Feedback     ThaiBuddhist Chronology  ThaiBuddhistChronology  java 8  ThaiBuddhistChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow

 Sample 14. Get 6 months before today as per JapaneseChronology

AbstractChronology abstractChrono = JapaneseChronology.INSTANCE;
System.out.println(abstractChrono.dateNow().minus(6, ChronoUnit.MONTHS));

   Like      Feedback     AbstractChronology  JapaneseChronology  ChronoUnit  java 8

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
 Sample 15. Filtering objects using google.common.base.Predicate

static Collection<Employee> employeesGreaterThan30(Collection<Employee> employees) {
return filter(employees, new Predicate<Employee>() {
public boolean apply(Employee employee) {
return employee.getAge() > 30;

   Like      Feedback     predicate  google.common.base.Predicate  filter objects   alternate for predicate before java 8  collections  google guava

 Sample 16. Java 8 Map Merge Example ( Map.merge )

Map<String,String> intMap = new HashMap<String,String>();
strMap.put("Key2", "Value2");
String str = strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints ue1Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=ue1Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections

 Sample 17. Java 8 MapMerge

Map<String,String> strMap = new HashMap<String,String>();
strMap.put("Key2", "Value2");
String str = strMap.merge("Key4","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=Value1, Key4=Value56}

   Like      Feedback     java 8  map.merge  map merge  hashmap  collections

 Sample 18. Use java.time.format.DateTimeFormatter to Parse date in the format YYYYMMDD+HHmmss

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4)
.appendValue(MONTH_OF_YEAR, 2)
.appendValue(DAY_OF_MONTH, 2)
.appendOffset("+HHMMss", "Z")

TemporalAccessor temporal = null;

try {
temporal = dateTimeFormatter.parse("2016101+235700");
System.out.println(temporal.toString()); // prints {OffsetSeconds=86220},ISO resolved to 2016-01-01
} catch (DateTimeParseException ex){
System.out.println("Error parsing date");

   Like      Feedback     DateTimeFormatter   Parse Date in Java 8   Parse date using DateTimeFormatter and DateTimeFormatterBuilder

 Sample 19. Count elements of a collection matching a Predicate using Apache Commons IterableUtils

List<String> list = new ArrayList();
list.add("New York");
list.add("New Jersey");

// <String> long org.apache.commons.collections4.IterableUtils.countMatches(Iterable<String> input, Predicate<? super String> predicate)
System.out.println(IterableUtils.countMatches(list, p->((String)p).startsWith("N")));

   Like      Feedback     Apache Commons IterableUtils  Apache Commons  Predicate  Java 8  Count elements of a collection  java8

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
 Sample 20. Concatenate two Streams

public static IntStream concat(IntStream a, IntStream b) {

Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
a.spliterator(), b.spliterator());
IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
return stream.onClose(Streams.composedClose(a, b));

   Like      Feedback     Concatenate two Streams   java 8  java8

 Sample 21. Usage of Java 8 Consumer interface

Consumer<String> consumer = s->{

consumer.accept("BuggyBread"); // prints BuggyBread

   Like      Feedback     Java 8 Consumer  Consumer interface

 Sample 22. Usage of java.util.function.BiPredicate

BiPredicate<String, String> predicate = (s1, s2) -> (s1.equals(s2));

System.out.println(predicate.test("BUGGY", "BREAD"));

   Like      Feedback     BiPredicate  Java 8 BiPredicate

 Sample 23. Averaging Group By using Java 8


Example -

Get Dept and it's average Salary,

   Like      Feedback     java 8

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner