Java @ Desk: Core Java 8 | Java at your desk

How to print a list or a collection using Lambda Expression in Java 8

How to print a list or a collection using Lambda Expression in Java 8

In this example, we will learn how to print a list using Lambda expression in Java 8. Traditional methods were using the normal for loop and use the System.out.println method to print the content of a collection.

There are 2 ways to print a list using Lambda expression -
1) Using lambda expression and functional operations
2) Using double colon operator in Java 8

Both these ways reduce the code to a single statement which is more readable and easy to maintain.

Below is the short example to demonstrate both the examples.
package com.lambda;

import java.util.ArrayList;
import java.util.List;

public class ForLoopPrint {

 public static void main(String args[]) {

  List<String> persons = new ArrayList<>();

  persons.add("John");
  persons.add("Adam");
  persons.add("Peter");
  persons.add("James");

  System.out.println("Using Old Loop");
  for (String person : persons) {
   System.out.print(person + "; ");
  }
  System.out.println("\n");

  System.out.println("Using lambda expression and functional operations");
  persons.forEach((person) -> System.out.print(person + "; "));

  System.out.println("\n");
  System.out.println("Using double colon operator in Java 8");
  persons.forEach(System.out::println);
 }
}


Here is the output -
Using Old Loop
John; Adam; Peter; James; 

Using lambda expression and functional operations
John; Adam; Peter; James; 

Using double colon operator in Java 8
John
Adam
Peter
James

Sorting a List using Lambda Expression in Java 8

Sorting a List using Lambda Expression in Java 8

In this post, we will learn how to sort a list using Lambda Expression in Java 8. In Java 6 or 7, Java pojo object must implements Comparator interface or Comparable interface to sort a collection of objects. The implementation need to be provided in compareTo method to sort a list based on particular property of a class.

In Java 8, the code has been reduced to just a single line. One can use the below 3 implementations:
1) sort method of List interface
2) sort method of Collections class
3) sort using stream() method of List interface

In 3rd strategy, the underlying list does not get sorted. So, either you must create a new object and assign the sorted list or assign the sorted list to the existing list object.
In both the implementations, the sorting logic goes as a Lambda expression.

Consider a Person class below in which sorting logic needs to be implemented on name of the person.
package com.pojo;

public class Person {

 private String id;

 private String name;

 private String address;

 public Person(String id, String name, String address) {
  super();
  this.id = id;
  this.name = name;
  this.address = address;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return this.id + ", " + this.name + ", " + this.address;
 }
}
Below one is the traditional sorting technique
Collections.sort(persons, new Comparator<Person>() {
   public int compare(Person p1, Person p2) {
    return p1.getName().compareTo(p2.getName());
   }
  });



Here is the implementation using Java 8 using Lambda expression
Collections.sort(persons, (p1, p2) -> p1.getName().compareTo(p2.getName()));

Collections.sort(persons, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));

persons.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

// Here, specifically the sorted list need to be assigned to a new list
// or existing list object.  
persons = persons.stream().sorted((p, p2) -> (p.getName().compareTo(p2.getName())))
 .collect(Collectors.toList());


Finally print the list using lambda expression
persons.forEach((person) -> System.out.print(person + "\n"));


Output
IdOne, Andy, Netherland
IdThree, Chris, London
IdTwo, John, Australia
IdFour, Nathan, Paris
IdFive, Peter, Brazil


LocalDateTime Add Hours to Date in Java 8

LocalDateTime Add Hours to Date in Java 8

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to add days to date:

1) plusHours - Takes an integer. Date will be incremented by number of hours.

2) plus - Takes an argument of class Duration.
The integer passed should be in number of hours.

Both these methods returns copy of LocalDateTime object.

package com.datentime;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class DateFormatter_Add {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");
 
 public static void addHoursToDateUsingPlusHours() {
  LocalDateTime sysTime = LocalDateTime.now();
  LocalDateTime one = sysTime.plusHours(1);
  System.out.println("System Time : \t" + sysTime.format(formatter));
  System.out.println("Time after one hour will be : \t"
    + one.format(formatter));
 }

 public static void addHoursToDateUsingPlusDuration() {
  LocalDateTime sysTime = LocalDateTime.now();
  System.out.println("System Time : \t" + sysTime.format(formatter));
  LocalDateTime one = sysTime.plus(Duration.ofHours(1));
  System.out.println("Time after one hour will be (using Duration): \t"
    + one.format(formatter));
 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  addHoursToDateUsingPlusHours();
  addHoursToDateUsingPlusDuration();
 }
}


Output:

System Time : 21-Aug-2014 12:26:35
Time after one hour will be : 21-Aug-2014 13:26:35
System Time : 21-Aug-2014 12:26:35
Time after one hour will be (using Duration): 21-Aug-2014 13:26:35


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

LocalDateTime Add Days to Date in Java 8

LocalDateTime Add Days to Date in Java 8

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to add days to date:

1) plusDays - Takes an integer. Date will be incremented by number of days.

2) plus - Takes an argument of class Duration.
The integer passed should be in number of days.

Both these methods returns copy of LocalDateTime object.

package com.datentime;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class DateFormatter_Add {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss"); 
 
 public static void addDaysToDateUsingPlusDays() {
  LocalDateTime today = LocalDateTime.now();
  LocalDateTime tomorrow = today.plusDays(1);
  System.out.println("Today is : \t" + today.format(formatter));
  System.out
    .println("Tommorow will be : \t" + tomorrow.format(formatter));
 }

 public static void addDaysToDateUsingPlusDuration() {
  LocalDateTime today = LocalDateTime.now();
  LocalDateTime tomorrow = today.plus(Duration.ofDays(1));
  System.out.println("Today is : \t" + today.format(formatter));
  System.out
    .println("Tommorow will be (Using Duration) : \t" + tomorrow.format(formatter));
 } 

 public static void main(String[] args) {
  // TODO Auto-generated method stub  
  addDaysToDateUsingPlusDays();
  addDaysToDateUsingPlusDuration();
 }
}


Output :

Today is : 21-Aug-2014 12:26:35
Tommorow will be : 22-Aug-2014 12:26:35
Today is : 21-Aug-2014 12:26:35
Tommorow will be (Using Duration) : 22-Aug-2014 12:26:35


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

LocalDateTime Add Weeks to Date in Java 8

LocalDateTime Add Weeks to Date in Java 8

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to subtract the hours from the date:

1) plusWeeks - Takes an integer. Date will be incremented by number of weeks.

2) plus - Takes an argument of class Duration.
The integer passed should be in number of days.

Both these methods returns copy of LocalDateTime object.

package com.datentime;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class DateFormatter_Add {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");

 
 public static void addWeeksToDateUsingPlusWeeks() {

  LocalDateTime xmas  = LocalDateTime.of(2013, Month.DECEMBER, 25, 0, 0);
  LocalDateTime newYear = xmas.plusWeeks(1);
  System.out.println("Christmas bells will ring from : \t" + xmas.format(formatter));
  System.out.println("New year will be on  : \t"
    + newYear.format(formatter));

 }

 public static void addWeeksToDateUsingPlusDuration() {
  
  LocalDateTime xmas  = LocalDateTime.of(2013, Month.DECEMBER, 25, 0, 0);
  LocalDateTime newYear = xmas.plus(Duration.ofDays(7));
  System.out.println("Christmas bells will ring from: \t" + xmas.format(formatter));
  System.out.println("New year will be on  : \t"
    + newYear.format(formatter));
 }
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  addWeeksToDateUsingPlusWeeks();
 addWeeksToDateUsingPlusDuration();
 
 }
}


Output :

Christmas bells will ring from : 25-Dec-2013 00:00:00
New year will be on  :  01-Jan-2014 00:00:00
Christmas bells will ring  from : 25-Dec-2013 00:00:00
New year will be on  :  01-Jan-2014 00:00:00


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

How to subtract seconds from Date using java 8 api

How to subtract seconds from Date using java 8 api

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to subtract the hours from the date:

1) minusSeconds - Takes an integer. Date will be reduced by given number of seconds

2) minus - Takes an argument of class Duration

Both these methods returns copy of LocalDateTime object.


In the below example, Date is initialized to 1st Jan 2014.
10 seconds are deducted using both the methods.


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class SubtractSecondsFromDate {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");

 
 
 public static void subSecondsFromDate_withMinusSeconds() {
        // Date is initialized to 1st Jan 2014
 LocalDateTime newYear = LocalDateTime.parse("2014-01-01T00:00:00");
  LocalDateTime newYearcountDown = newYear.minusSeconds(10);
 System.out.println("Lets the count down begin    : \t"
    + newYearcountDown.format(formatter));
 System.out.println("Happy New Year   : \t" + newYear.format(formatter));
  
 }

 public static void subSecondsFromDate_usingMinusDurationofSeconds() {

      // Date is initialized to 1st Jan 2014
  LocalDateTime newYear = LocalDateTime.parse("2014-01-01T00:00:00");
   LocalDateTime newYearcountDown = newYear.minus(Duration.ofSeconds(10));
  System.out.println("Lets the count down begin    : \t"
     + newYearcountDown.format(formatter));
  System.out.println("Happy New Year  (using Duration) : \t" + newYear.format(formatter));
 }

 public static void main(String[] args) {
  
  subSecondsFromDate_withMinusSeconds();
  subSecondsFromDate_usingMinusDurationofSeconds();

 }
}


Output :

Lets the count down begin : 31-Dec-2013 23:59:50
Happy New Year : 01-Jan-2014 00:00:00
Lets the count down begin : 31-Dec-2013 23:59:50
Happy New Year  (using Duration) :  01-Jan-2014 00:00:00


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

How to subtract minutes from Date using java 8 api

How to subtract minutes from Date using java 8 api

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to subtract the hours from the date:

1) minusMinutes - Takes an integer. Date will be reduced by given number of minutes
2) minus - Takes an argument of class Duration

Both these methods returns copy of LocalDateTime object.

This time we will use the (to) factory of LocalDateTime and pass the custom parameters. Let’s say your cake should be ready by half an hour. All the core classes in the new API are constructed by fluent factory methods. When constructing a value by its constituent fields, the factory is called of;

In the below example, Date is initialized to 5th DECEMBER 2014.
30 minutes are deducted using both the methods.


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class SubtractMinutesFromDate {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");

 
 public static void subMinutesFromDate_withMinusMinutes() {
        // Date is initialized to 5th DECEMBER 2014
  LocalDateTime birthday = LocalDateTime.of(2014, Month.DECEMBER, 5, 0, 0); 
  LocalDateTime birthdayParty = birthday.minusMinutes(30);
  System.out.println("Birthday Bash   : \t" + birthday.format(formatter));
  System.out.println("But cake should be ready by    : \t"
    + birthdayParty.format(formatter));

 }

 public static void subMinutesFromDate_usingMinusDurationofMins() {

      // Date is initialized to 5th Dec 2014
   LocalDateTime birthday = LocalDateTime.of(2014, Month.DECEMBER, 5, 0, 0); 
   LocalDateTime birthdayParty = birthday.minus(Duration.ofMinutes(30));
   System.out.println("Birthday Bash   : \t" + birthday.format(formatter));
   System.out.println("But cake should be ready by   (using Duration) : \t"
     + birthdayParty.format(formatter));
 }
 
 

 public static void main(String[] args) {
  subMinutesFromDate_withMinusMinutes();
  subMinutesFromDate_usingMinusDurationofMins();
 }
}


Output :

Birthday Bash : 05-Dec-2014 00:00:00
But cake should be ready by : 04-Dec-2014 23:30:00
Birthday Bash : 05-Dec-2014 00:00:00
But cake should be ready by   (using Duration) : 04-Dec-2014 23:30:00


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.

How to subtract hours from Date using java 8 api

How to subtract hours from Date using java 8 api

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to subtract the hours from the date:

1) minusHours
2) minus

Both these methods returns copy of LocalDateTime object.


We are using LocalDateTime.now(); to get current system time.

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class SubtractHoursFromDate {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");

 public static void subHoursFromDate_withMinusHours() {

  LocalDateTime sysTime = LocalDateTime.now();
  LocalDateTime one = sysTime.minusHours(1);
  System.out.println("System Time : \t" + sysTime.format(formatter));
  System.out.println("System Time Minus one hour: \t" + one.format(formatter));

 }

 public static void subHoursFromDate_usingMinusDuration() {

  LocalDateTime sysTime = LocalDateTime.now();
  System.out.println("System Time : \t" + sysTime.format(formatter));
  LocalDateTime one = sysTime.minus(Duration.ofHours(1));
  System.out.println("System Time Minus one hour (using Duration): \t" + one.format(formatter));
 }

 

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  subHoursFromDate_withMinusHours();
  subHoursFromDate_usingMinusDuration();
  

 }


Output:

System Time :  20-Aug-2014 20:53:37
System Time Minus one hour:  20-Aug-2014 19:53:37
System Time :  20-Aug-2014 20:53:37
System Time Minus one hour (using Duration):  20-Aug-2014 19:53:37


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.