How to Delete folder and subfolders using Java 8

  • How to delete folder with all files and sub folders in it using java 8.
  • We can use java 8 Stream to delete folder recursively 
  • Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  • .sorted(Comparator.reverseOrder())
  • .map(Path::toFile)
  • .peek(System.out::println)
  • .forEach(File::delete);

  1. Files.walk -  this method return all files/directories below the parent folder
  2. .sorted - sort the list in reverse order, so the folder itself comes after the including subfolders and files
  3. .map - map the file path to file
  4. .peek - points to processed entry
  5. .forEach - on every File object calls the .delete() method 




#1: Java Example program to delete folders and subfolders using java 8 stream

  1. package com.instanceofjava;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.FileVisitOption;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.util.Comparator;
  9. /**
  10.  * @author www.Instanceofjava.com
  11.  * @category interview questions
  12.  * 
  13.  * Description: delete folders and sub folders using java 8
  14.  *
  15.  */

  16. public class DeleteFolder {

  17. public static void main(String[] args) {
  18. Path rootPath = Paths.get("C:\\Users\\Saidesh kilaru\\Desktop\\folder1");
  19. try {
  20. Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  21.     .sorted(Comparator.reverseOrder())
  22.     .map(Path::toFile)
  23.     .peek(System.out::println)
  24.     .forEach(File::delete);
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }

  29. }

Output:

  1. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder\file2 in sub folder.docx
  2. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder
  3. C:\Users\Saidesh kilaru\Desktop\folder1\file1.docx
  4. C:\Users\Saidesh kilaru\Desktop\folder1



How to Convert integer set to int array using Java 8

  • How to convert Integer Set to primitive int array.
  • By Using java 8 Streams we can convert Set to array.
  • set.stream().mapToInt(Number::intValue).toArray();
  • Lets see an example java program on how to convert integer set to int array using java 8

#1: Java Example program on converting Integer Set to int Array

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class SetToArray {
  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programming questions
  9.  * 
  10.  * Description: convert Integer set to int array using java 8
  11.  *
  12.  */
  13. public static void main(String[] args) {
  14. Set<Integer> hashset= new HashSet<>(Arrays.asList(12,34,56,78,99));
  15. int[] array = hashset.stream().mapToInt(Number::intValue).toArray();
  16. for (int i : array) {
  17. System.out.println(i);
  18. }

  19. }

  20. }

Output:

  1. 34
  2. 99
  3. 56
  4. 12
  5. 78





integer set to integer array java


In Java, a Set is a collection that contains no duplicate elements and is unordered. To convert a Set to an array, you can use the toArray() method of the Set interface. This method returns an array containing all of the elements in the Set in the order they are returned by the iterator.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

Integer[] array = set.toArray(new Integer[set.size()]);



In this example, we first create a HashSet of integers, add some elements to it, then we use the toArray method to convert it to an array of integers.

toArray(T[] a) method where we can pass an empty array of a specific type, the method will fill the array with the elements from the set, this is useful if you know the size of the array that you need.

converting a Set to an array in Java can be done using the toArray() method of the Set interface. The method returns an array containing all of the elements in the Set in the order they are returned by the iterator. This method can also accept an empty array of a specific type, the method will fill the array with the elements from the set.

Initializing a boolean array in java with an example program

  • Initializing a boolean variable : boolean b=true;
  • In some cases we need to initialize all values of boolean array with true or false.
  • In such cases we can use Arrays.fill() method
  • Arrays.fill(array, Boolean.FALSE);
  • java initialize boolean array with true:  Arrays.fill(array, Boolean.FALSE);
  • Lets see an example java program on how to assign or initialize boolean array with false or true values.



#1: Java Example program on initializing boolean array.

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview questions
  6.  * 
  7.  * Description: Initialize boolean array values with false or true
  8.  *
  9.  */
  10. public class InitializeBoolean {

  11. public static void main(String[] args) {
  12. Boolean[] array = new Boolean[4];
  13. //initially all values will be null
  14. for (int i = 0; i < array.length; i++) {
  15. System.out.println(array[i]);
  16. }
  17. Arrays.fill(array, Boolean.FALSE);
  18. // all values will be false
  19. for (int i = 0; i < array.length; i++) {
  20. System.out.println(array[i]);
  21. }
  22. Arrays.fill(array, Boolean.TRUE);
  23. // all values will be false
  24. for (int i = 0; i < array.length; i++) {
  25. System.out.println(array[i]);
  26. }
  27. }

  28. }

Output:

  1. null
  2. null
  3. null
  4. null
  5. false
  6. false
  7. false
  8. false
  9. true
  10. true
  11. true
  12. true


java initialize boolean array with true

Java 8 initialize set with values with an example program

  • We can initialize set while defining by passing values to constructor.
  • For example to initialize HashSet we can use Arrays.asList(value1,value2).
  • Set<Integer> hashset = new HashSet<>(Arrays.asList(12, 13));

#1: Java Example program to initialize set without using java 8

  1. import java.util.Arrays;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5.  * @author www.Instanceofjava.com
  6.  * @category interview questions
  7.  * 
  8.  * Description: Initialize set 
  9.  *
  10.  */
  11. public class InitializeSet {

  12. public static void main(String[] args) {

  13. Set<Integer> hashset = new HashSet<>(Arrays.asList(12, 13));
  14. System.out.println(hashset);
  15. }

  16. }

Output:

  1. [12, 13]


  • We can initialize set in java 8 using Stream.
  • Stream.of("initialize", "set").collect(Collectors.toSet());



#2: Java Example program to initialize set without using java 8

  1. import java.util.Set;
  2. import java.util.stream.Collectors;
  3. import java.util.stream.Stream;
  4. /**
  5.  * @author www.Instanceofjava.com
  6.  * @category interview questions
  7.  * 
  8.  * Description: Initialize set using java 8 Stream
  9.  *
  10.  */
  11. public class InitializeSet {

  12. public static void main(String[] args) {

  13. Set<String> set = Stream.of("initialize", "set").collect(Collectors.toSet());
  14. System.out.println(set);
  15. }

  16. }



Output:

  1. [set, initialize]


  • We can initialize Set in java 8 by creating stream from an Array and list


#3: Java Example program to initialize set without using java 8


java 8 initialize set with values with an example program

Top 10 Java array example programs with output

1.Java Example program to find missing numbers in an array.


2. Java interview Example program to find second maximum number in an integer array


3.Java Practice programs on arrays: find second smallest number.


4. How many ways we can print arrays in java: lets check below link for 5 different ways.


5.Advantages and disadvantages of arrays




6. Benefits of arraylist over arrays


7. Creating Array of objects in java 


8. Find top two maximum numbers in an array : java array practice programs


9. Remove duplicates from an array java


10. Sort integer array using Bubble Sort in java


How to run multiple java programs simultaneously in eclipse

  • In some cases we may need to run two java programs simultaneously and need to observe the ouput of two progarsms. In such cases we need to run multiple java programs parallel.  
  • Now we will see how to run two java programs simultaneously
  • First thing we need to understand is we can run multiple java programs at a time in eclipse.
  • Second thing is we can view multiple consoles in eclipse.   



#1. How can we open multiple consoles in eclipse?

  • In Eclipse console window right side we will have one rectangular box with Plus symbol on it to open a new console. by clicking on it we can open a new console view.

open multiple consoles  view in eclipse


2: Create two java programs.

ClassOne:
  1. package com.instanceofjava;

  2. public class ClassOne {
  3. /**
  4. * @author www.Instanceofjava.com
  5. * @category interview questions
  6. * Description: how to run two java programs simultaneously
  7. *
  8. */
  9. public static void main(String[] args) throws InterruptedException {

  10. for (int i = 0; i < 100; i++) {
  11. Thread.sleep(1000);
  12. System.out.println(i);
  13. }
  14. }
  15. }

ClassTwo
  1. package System.out;

  2. public class ClassTwo {
  3. /**
  4. * @author www.Instanceofjava.com
  5. * @category interview questions
  6. * Description: how to run two java programs simultaneously
  7. *
  8. */
  9. public static void main(String[] args) throws InterruptedException {
  10. for (int i = 100; i < 200; i++) {
  11. System.out.println(i);
  12. Thread.sleep(1000);
  13. }


  14. }

  15. }


  • Run ClassOne and ClassTwo.
  • Pin console.

pin console.png



  • You can see both the running programs with output with different console views.
how to run two java programs simultaneously

Log4j example in java using properties file

  • Logging is very important part of programming. Logging helps programmer to understand process flow and identify the problems where actually occurred.
  • Log4J will be configured externally using properties file. We can print the logging statements in the console or we can push them in to a log file based on the requirement.
  •  org.apache.log4j class will provide required classes to implement logging
  • We need to add Log4J dependency in our project.
  • Create instance of logger by using Logger.getLogger(Log4JExample.class);
  • Lets see how to create log4j.properties file in eclipse



1. Create a maven project and add Log4J dependency:


how to create log4j.properties file in eclipse

2. Create log4j.properties file


log4j.properties example file

  1. log4j.rootLogger=INFO, console

  2. log4j.appender.console=org.apache.log4j.ConsoleAppender

  3. log4j.appender.console.layout=org.apache.log4j.PatternLayout
  4. log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz}

3.Create java example program to read log4j.properties file

  1. import org.apache.log4j.BasicConfigurator;
  2. import org.apache.log4j.Logger;

  3. public class Log4JExample {

  4. static Logger logger = Logger.getLogger(Log4JExample.class);
  5.     public static void main(String[] args)
  6.     {
  7.     BasicConfigurator.configure();
  8.     logger.info("main method start!!");
  9.    
  10.     System.out.println("hi");
  11.     logger.info("log4j properties configuration example");
  12.      
  13.     logger.info("main method end!!");
  14.     }
  15. }

Output:

  1. 2018-02-08 23:09:10.747 IST0 [main] INFO Log4JExample  - main method start!!
  2. hi
  3. 2018-02-08 23:09:10.752 IST5 [main] INFO Log4JExample  - log4j properties configuration example
  4. 2018-02-08 23:09:10.753 IST6 [main] INFO Log4JExample  - main method end!!

Java program to reverse ArrayList elements

  • How to reverse an ArrayList in java.
  • By using Collections.reverse() method we can reverse ArrayList in java.



#1: Java Example program to reverse ArrayList 

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Collections;

  4. public class ReverseArrayList {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview questions
  8. * Description: Java Example program to reverse an ArrayList
  9. *
  10. */
  11. public static void main(String[] args) {
  12. ArrayList<String> arrayList= new ArrayList<>();
  13. arrayList.add("Apple");
  14. arrayList.add("Banana");
  15. arrayList.add("Orange");
  16. Collections.reverse(arrayList);
  17. System.out.println(arrayList);
  18. }

  19. }


Output:

  1. [Orange, Banana, Apple]


#2: Java Example program to print arraylist in reverse order 


reverse arraylist in java example program

How to convert list to set in java with example program

  • Java program to convert list to set.
  • Convert ArrayList of string to HashSet in java example program
  • How to convert List to Set in java 
  • Set<String> strSet = new HashSet<String>(arrList);
  • HashSet having a constructor which will take list as an argument.
  • Lets see how to convert list to Set using java program.



#1: Java Example Program to Convert List to Set.


  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = new HashSet<String>(arrList);
  18. System.out.println(strSet);

  19. }

  20. }

Output:

  1. [Java, Example Program, List to String]

  • Using java.util.stream we can convert List to set in java 8
  • We can use java 8 java.util.stream.Collectors
  • arrList.stream().collect(Collectors.toSet());

#2: Java Example program to convert List to Set using java 8.

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.Set;
  4. import java.util.stream.Collectors;

  5. public class ListToSet {
  6. /**
  7. * @author www.Instanceofjava.com
  8. * @category interview questions
  9. * Description: Convert List to set in java with example program
  10. *
  11. */
  12. public static void main(String[] args) {
  13. ArrayList<String> arrList= new ArrayList<>();
  14. arrList.add("Java");
  15. arrList.add("List to String");
  16. arrList.add("Example Program");
  17. Set<String> strSet = arrList.stream().collect(Collectors.toSet());
  18. System.out.println(strSet);

  19. }

  20. }


Output:

java convert list to set

How to convert list to comma separated string using java 8

  • Howto convert list to comma separated string using java 8 stream.
  • By using collect() method of stream  and Collectors.join(",") method we can convert list to comma separated string in java 8.
  • Java Example program to convert list of strings to comma separated string.



#1: Java Example program to convert list to comma separated string using java 8 stream.

  1. package com.instanceofjava;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.stream.Collectors;

  5. /**
  6.  * @author www.Instanceofjava.com
  7.  * @category interview programming questions
  8.  * 
  9.  * Description: convert ArrayList of strings tp comma separated string using java 8
  10.  *
  11.  */
  12. public class ArrayToString {

  13. public static void main(String[] args) {
  14. ArrayList<String> colours =new ArrayList<>();
  15. colours.add("Red");
  16. colours.add("Green");
  17. colours.add("Orange");
  18.    String result = colours.stream().collect(Collectors.joining(","));
  19.    System.out.println(result);
  20.    
  21. }
  22. }


Output:
  1. Red,Green,Orange


convert list to comma separated string using java 8

How to remove square brackets from string in java

  • Remove square brackets from string in java.
  • We can remove square brackets from string by  using regular expressions.
  • By using regular expressions we can remove any special characters from string.
  • Now , we will check how to remove brackets from a string using regular expressions in java.



#1: Java Example program to remove brackets from string using regex.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: remove square brackets from string 
  7.  *
  8.  */
  9. public class ArrayToString {

  10. public static void main(String[] args) {
  11.  String strbrackets = "[String nundi ][brackets][remove cheyyadam][yela?]";
  12.  strbrackets = strbrackets.replaceAll("\\[", "").replaceAll("\\]","");
  13.  System.out.println(strbrackets);
  14.  
  15. }
  16. }


Output:

  1. String nundi bracketsremove cheyyadamyela?


#2: Java program to remove curly brackets from string 



remove square brackets from string java curly

How to convert array to string without brackets in java

  • Converting array to string and string should not contain any brackets.
  • We can convert array to string by iterating array and capturing each element from an array and append to StringBuilder/StringBuffer so that final output will be string without brackets.
  • Lets see an example java program to convert array to string by removing brackets.
  • So that we can remove brackets from string.



#1 : Java Example program to convert array to string without brackets.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: convert array to string without brackets.
  7.  *
  8.  */
  9. public class ArrayToString {

  10. public static void main(String[] args) {
  11.  String array[]= {"java","string","without","brackets"};
  12.  StringBuffer strbuffer = new StringBuffer();
  13.  for (String str : array) {
  14.   strbuffer.append(str).append(" ");
  15.  }
  16.  String result = strbuffer.toString();
  17.  System.out.println(result);
  18.  
  19. }

  20. }

Output:

  1. java string without brackets 



convert array to string without brackets

Java Program to convert ArrayList to String array

  • Java code to convert arraylist to string array.
  • We can convert ArrayList of strings to String array by using  toArray() method.
  • Lets see an Example java program to convert ArrayList to string array.



#1:  Java example program to convert ArrayList to String Array

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. public class ArrayListToStringArray {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview programs
  8. * Description: Java Prorgam to convert ArrayList to String array
  9. *
  10. */
  11. public static void main(String[] args) {
  12. List<String> lstflowers = new ArrayList<String>();
  13. lstflowers.add("Rose");
  14. lstflowers.add("Lilly");

  15. String[] arrayflower = new String[lstflowers.size()];
  16. arrayflower = lstflowers.toArray(arrayflower);

  17. for(String flower : arrayflower)
  18.     System.out.println(flower);
  19. }

  20. }


Output:


  1. Rose
  2. Lilly

#2:  Java example program to convert ArrayList to String Array Using java 8

  1. package com.instanceofjava;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. public class ArrayListToStringArray {
  5. /**
  6. * @author www.Instanceofjava.com
  7. * @category interview programs
  8. * Description: Java Prorgam to convert ArrayList to String array using java 8
  9. *
  10. */
  11. public static void main(String[] args) {
  12. List<String> lstflowers = new ArrayList<String>();
  13. lstflowers.add("Rose");
  14. lstflowers.add("Lilly");

  15. String[] arrayflower = lstflowers.toArray(new String[lstflowers.size()]);

  16. for(String flower : arrayflower)
  17.     System.out.println(flower);
  18. }

  19. }


java program to convert arraylist to string array

Java 8 subtract N minutes from current date

  • Java 8 provides java.time.LocalDateTime class.
  • By using minusMinutes() methods of LocalDateTime class we can subtract minutes from date or current date in java.
  • Lets see an example program on how to remove / subtract n minutes from current date using java 8.



  1. package com.instanceofjava.java8;

  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: subtract minutes to current date using java 8
  8.  *
  9.  */
  10. public class AddMinutesToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13.     LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before subtracting 30 minutes to date: "+datetime);
  15.     //add seconds by using minuesMinutes(seconds) method
  16. datetime=datetime.minusMinutes(30);
  17. System.out.println("After subtracting 30 minutes to date: "+datetime);

  18. }

  19. }

Output:

  1. Before subtracting 30 minutes to date: 2018-02-05T22:41:42.463
  2. After subtracting 30 minutes to date: 2018-02-05T22:11:42.463


subtract minutes from java 8 date time.png

How to Add N minutes to current date using java 8

  • Java 8 providing java java.time package which is having more utility methods related to date and time.
  • LocalDateTime class providing plusMinutes(int minutes) method to add minutes to current date or given date in java.
  • Lets see an example program to add 30 minutes to current date using java 8 LocalDateTime class.



#1: Java Example program to add 30 minutes to current date 

  1. package com.instanceofjava.java8;

  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: Add minutes to current date using java 8
  8.  *
  9.  */
  10. public class AddMinutesToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13.     LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before adding minutes to date: "+datetime);
  15.     //add seconds by using plusMinutes(Minutes) method
  16. datetime=datetime.plusMinutes(30);
  17. System.out.println("After adding 30 minutes to date: "+datetime);

  18. }

  19. }



Output:


  1. Before adding minutes to date: 2018-02-05T22:14:33.664
  2. After adding 30 minutes to date: 2018-02-05T22:44:33.664



add minutes to current date java 8


Can we define default methods in functional interfaces in java 8

  • Functional interfaces in java 8 will have single abstract method in it.
  • Check below two pages regarding defining and using functional interfaces using Lamda expressions.
  • Java 8 functional interface with example
  • Implement java 8 functional interface using lambda example program
  • We can define default methods in functional interfaces in java 8.
  • But every functional interface must have single abstract method in it.
  • As we know that default methods should have a implementation as they are not abstract methods.
  • Lets see an example program on defining functional interface with default method.



#1:  Java example program to create functional interface with default method.

  1. package com.instanceofjava.java8;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 functional interfaces
  7.  *
  8.  */
  9. @FunctionalInterface
  10. public interface FunctionalInterfaceExample {
  11.  
  12. void show();
  13.         //default method
  14. default void message() {
  15. System.out.println("hello this is default method in functional interface");
  16. }
  17. }


#2: Java Example program on how to implement functional interface abstract method and use default method.


Can we define default methods in functional interfaces in java 8


Functional interface with multiple methods in java 8

  • Functional interfaces will contains single abstract method with @FunctionalInterface annotation.
  • Check below two posts for defining functional interface and implementing functional interface method using Lamda in java 8.
  • Java 8 functional interface with example
  • Implement java 8 functional interface using lambda example program
  • Now the question is can we declare or define multiple abstract methods in one functional interface in java 8.
  • No. Functional interface should contain only one abstract method so that Lamda will implement it.
  • Lets see what happens if we define multiple abstract methods inside a functional interface
  • Note: all methods inside any interface by default abstract methods.



  1. package com.instanceofjava.java8;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 functional interfaces
  7.  *
  8.  */
  9. @FunctionalInterface
  10. public interface FunctionalInterfaceExample {
  11. //compile time error: Invalid '@FunctionalInterface' annotation; FunctionalInterfaceExample is
  12. not a functional interface
  13.  
  14. void show();
  15. void calculate();
  16. }


  • If we define multiple abstract methods inside a functional interface it will throw a compile time error.
  • Invalid '@FunctionalInterface' annotation; FunctionalInterfaceExample is not a functional interface

Implement java 8 functional interface using lambda example program

  • Functional interfaces introduces in java 8 .
  • Functional interfaces will have single abstract method in it.
  • Check here for full details on Java 8 functional interface with example.
  • Functional interfaces will be implemented by java 8 Lamda expressions.
  • Lets see an example program on how can we use functional interfaces or how can we implement functional interfaces using Lamda expression in java 8.
  • Create one functional interface with one abstract method in it.
  • Create a class and implement this abstract method using Lamda Expressions.



#1: Java example program to create functional interface.

functional interface example in java 8 using lamda expressions


#2: Java example program to implement functional interface using Lamda expressions in java 8.

  1. package com.instanceofjava.java8;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 Lamda expressions
  7.  *
  8.  */
  9. public class LamdaExpressions {

  10. public static void main(String[] args) {
  11. FunctionalInterfaceExample obj = ()->{
  12. System.out.println("hello world");
  13. };

  14. obj.show();
  15. }

  16. }

Output:

  1. hello world

Java 8 functional interface with example

  • Java 8 introduced Lamda expressions and functional interfaces.
  • An interface with one abstract method is known as functional interfaces.
  • Functional interfaces in java 8 marked with @FunctionalInterface.
  • These functional interfaces implementation will be provided by Lamda expressions.
  • Default methods in java 8 interfaces are not abstract methods. But we can define  multiple default methods in functional interface.
  • Java 8 functional interface example program


#1: Java Example program to create java 8 functional interface.


  1. package com.instanceofjava.java8;

  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programming questions
  5.  * 
  6.  * Description: java 8 functional interfaces
  7.  *
  8.  */
  9. @FunctionalInterface
  10. public interface FunctionalInterfaceExample {

  11. void show();
  12. }


  • Can we create functional interface with @FunctionalInterface annotation without any single abstract method?
  • No. Functional interfaces must have single abstract method inside it.
  • It will throw compile time error : Invalid '@FunctionalInterface' annotation; FunctionalInterfaceExample is not a functional interface.
  • Lets see an example program on this so that we can conclude it.
  • How to use these functional interfaces we will discuss in next post on Lamda expressions.
  • Implement java 8 functional interface using lambda example program


#2: What will happend if we define functional interface without a single abstract method in it?

functional interface example in java 8

Java 8 date add n seconds to current date example program

  • Java 8 providing java.time.LocalDateTime class.
  • By using plusSeconds() method of  LocalDateTime we can add seconds to date.
  • By Using minusSeconds() method we can substract  seconds from java date.
  • Lets see an example java program to add n seconds to current date and minus / subtract n seconds from java 8 date. 



#1: Java Example program to add n seconds to current date using java 8.

  1. package com.instanceofjava.java8;
  2. import java.time.LocalDateTime;

  3. /**
  4.  * @author www.Instanceofjava.com
  5.  * @category interview programs
  6.  * 
  7.  * Description: java seconds to java 8 date
  8.  *
  9.  */
  10. public class addSecondsToDate {

  11. public static void main(String[] args) {
  12. //create data using java 8 LocalDateTime 
  13. LocalDateTime datetime= LocalDateTime.now();
  14. System.out.println("Before: "+datetime);
  15. //add seconds by using plusSeconds(seconds) method
  16. datetime=datetime.plusSeconds(12);
  17. System.out.println("After: "+datetime);
  18. }

  19. }

Output:
  1. 2018-02-03T20:19:25.760
  2. 2018-02-03T20:19:37.760

#2: Java Example program to subtract n seconds to current date using java 8.


java 8 date subtract seconds  example program

Java 8 stream filter method example program

  • We can use java 8 stream class filter method to filter the values from a list /map in java
  • By Using filter() and collect() methods of stream class we can achieve this.
  • Lets see an example program to filter value from list without using java 8 streams and with java 8 stream filter.



#1: Java Example program to filter . remove value from list without using java 8 stream

  1. package com.instanceofjava.filtermethodjava8

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;

  5. /**
  6.  * @author www.Instanceofjava.com
  7.  * @category interview programs
  8.  * 
  9.  * Description: Remove value from list without using java 8 stream filter method
  10.  *
  11.  */
  12. public class fillterListJava8{
  13. private static List<String> filterList(List<String> fruits, String filter) {
  14.         List<String> result = new ArrayList<>();
  15.         for (String fruit : fruits) {
  16.             if (!filter.equals(fruit)) { 
  17.                 result.add(fruit);
  18.             }
  19.         }
  20.         return result;
  21.     }
  22. public static void main(String[] args) {
  23. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  24.  
  25. System.out.println("Before..");
  26.  
  27. for (String str : fruits) {
  28.             System.out.println(str);    
  29.         }
  30.  
  31.         List<String> result = filterList(fruits, "lemon");
  32.         System.out.println("After..");
  33.         for (String str : result) {
  34.             System.out.println(str);    
  35.         }
  36. }
  37. }

Output:
  1. Before..
  2. apple
  3. banana
  4. lemon
  5. After..
  6. apple
  7. banana

#2: Java Example program to filter . remove value from list using java 8 java.util.stream

  1. package com.instanceofjava.java8;

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.stream.Collectors;

  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programs
  9.  * 
  10.  * Description: Remove value from list using java 8 stream filter method
  11.  *
  12.  */

  13. public class filterMethodOfStream {

  14. public static void main(String[] args) {
  15. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  16. String value="lemon";
  17. List<String> result = fruits.stream()                
  18.                 .filter(line -> !value.equals(line))     
  19.                 .collect(Collectors.toList());             
  20.         result.forEach(System.out::println); 
  21.        
  22.         for (String str : result) {
  23.             System.out.println(str);    
  24.         }
  25. }

  26. }






Output:


java 8 stream filter method
Select Menu