Core Java

Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


Advertisements

Java 8 – Sorted Map By Key & Value

Posted on

Java-8

 

 

 

Below example will show, how to sort Collection & Map element by Key & Value using Lambda Expression in Java 8.

Example 1

In this example, we will see how to sort  element of Collection using Lambda expression.


        List listOfString = new ArrayList<>();
        listOfString.add("Z");
        listOfString.add("Q");
        listOfString.add("D");
        listOfString.add("A");
        listOfString.add("H");
        listOfString.add("T");

        listOfString.stream().sorted((e1,e2)->e1.compareTo(e2)).forEach(e->{
            System.out.println(" sorted list of String "+e);
        });
        // return new sorted list.
        /*        
        listOfString = listOfString.stream()
                                   .sorted((e1,e2)->e1.compareTo(e2))
                                   .collect(Collectors.toList());
        listOfString.forEach(e->{
            System.out.println(" sorted list of String "+e);
        });*/

Output:-
sorted list of String A
sorted list of String D
sorted list of String H
sorted list of String Q
sorted list of String T
sorted list of String Z

Example 2 : See how to sort a List’s Person by Name.

 


        List list = new ArrayList();

        list.add(new Person(6, "FF", 13, Person.SEX.MALE, "GOA"));
        list.add(new Person(7, "GG", 31, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(8, "HH", 30, Person.SEX.MALE, "Mumbai"));
        list.add(new Person(9, "II", 22, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(1, "AA", 12, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(2, "BB", 22, Person.SEX.FEMALE, "MP"));
        list.add(new Person(3, "CC", 44, Person.SEX.FEMALE,"UP"));
        list.add(new Person(4, "DD", 25, Person.SEX.MALE, "Gurgaon"));
        list.add(new Person(5, "EE", 51, Person.SEX.FEMALE, "GOA"));

         // sorted Person by name
        List sortedList = list.stream()
                .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                .collect(Collectors.toList());
        sortedList.forEach(p->System.out.println("sorted by name :: "+p.toString()));


output :-
sorted by name :: Person{id=1, name=’AA’, age=12, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=2, name=’BB’, age=22, gender=FEMALE, location=’MP’}
sorted by name :: Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’UP’}
sorted by name :: Person{id=4, name=’DD’, age=25, gender=MALE, location=’Gurgaon’}
sorted by name :: Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’GOA’}
sorted by name :: Person{id=6, name=’FF’, age=13, gender=MALE, location=’GOA’}
sorted by name :: Person{id=7, name=’GG’, age=31, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=8, name=’HH’, age=30, gender=MALE, location=’Mumbai’}
sorted by name :: Person{id=9, name=’II’, age=22, gender=FEMALE, location=’Delhi’}

Example 3:- See how to sort a Map by value element


        //Sort a Map by their Value.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [5=a, 9=c, 3=f, 6=k, 1=z]

Example 4:- See how to sort a Map by Key element


        //Sort a Map by their Key.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [1=z, 3=f, 5=a, 6=k, 9=c]

Example 5:-

Here, A Map<String,Person> is created where String & Person object are taken as a Key & Value elements. First we will sort by Key elements then sort by Value elements in this below example.

Sorted by Map’s Key –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream()
                .sorted((e1,e2)->e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 

a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}

Final output give us a Map which values are sorted location field –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
                e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}

 

There are lots of ways to do this work depends on the requirement. Hope you enjoy this post.
Thanks
——–

Java 8 – Predicate Example

Posted on Updated on

Java-8

 

 

 

Predicate:-

Predicates represent single argument functions that return a boolean value. It can be applied to any Collection/group of similar Objects that is evaluated by a Predicate  condition.

A Predicate is a Functional Interface,we can pass lambda expressions wherever predicate is expected. Although Predicate is not only a Functional Interface in Java 8 but a set of standard  Functional Interfaces are given for developer in Java 8 as below :-

  • Predicate: A property of the object passed as argument
  • Consumer: An action to be performed with the object passed as argument
  • Function: Transform a T to a U
  • Supplier: Provide an instance of a T (such as a factory)
  • UnaryOperator: A unary operator from T -> T
  • BinaryOperator: A binary operator from (T, T) -> T

Below is simple defined Predicate  by inline lambda expression:-


Predicate checkFemale = (p)->p.getGender()==SEX.FEMALE;
Predicate checkMale = (p)->p.getGender()==SEX.MALE;
Predicate checkJuniorMalePerson = (p)->p.getGender()==SEX.MALE && p.getAge() <=18;
Predicate checkSeniorFemalePerson = (p)->p.getGender()==SEX.FEMALE && p.getAge() > 18;
Predicate checkNCRRegionPerson = (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
					|| p.getLocation().equalsIgnoreCase("Noida")
					|| p.getLocation().equalsIgnoreCase("Gurgaon");

 

In the below example,  We have a list of Employee Object having some pre-defined properties and base on a condition or set of conditions, group of Objects get evaluated.



import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.example.model.Person.SEX;

public class PersonPredicateTest {

	public static void main(String args[]) {
		Person person1 = new Person(1, "AA", 12, SEX.FEMALE, "Delhi");
		Person person2 = new Person(2, "BB", 22, SEX.FEMALE, "MP");
		Person person3 = new Person(3, "CC", 44, SEX.MALE, "UP");
		Person person4 = new Person(4, "DD", 25, SEX.MALE, "Gurgaon");
		Person person5 = new Person(5, "EE", 51, SEX.FEMALE, "GOA");
		Person person6 = new Person(6, "FF", 13, SEX.MALE, "GOA");
		Person person7 = new Person(7, "GG", 31, SEX.FEMALE, "Delhi");
		Person person8 = new Person(8, "HH", 30, SEX.MALE, "Mumbai");
		Person person9 = new Person(9, "II", 22, SEX.FEMALE, "Delhi");

		List listOfEmployee = new ArrayList<>(Arrays.asList(
				new Person[] { person1, person2, person3, person4, person5, person6, person7, person8, person9 }));

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkFemale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkMale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Person who is living in NCR Region
		System.out.println("############ Get All Junior Person who is living in NCR Region ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkNCRRegionPerson())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Junior Female ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Junior Male
		System.out.println("############ Get All Junior Male ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Delhi Regional Senior Person
		System.out.println("############ Get All Delhi Regional Senior Person ##############");
		Collection listOfDelhiRegionPerson = process(listOfEmployee,
				checkSeniorPerson().and(checkRegion("delhi")));
		listOfDelhiRegionPerson.forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Senior Female
		System.out.println("############ Get All Senior Female ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Senior Male
		System.out.println("############ Get All Senior Male ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

	}

	private static Predicate checkJuniorPerson() {
		return (p) -> p.getAge() <= 18;
	}

	private static Predicate checkSeniorPerson() {
		return (p) -> p.getAge() > 18;
	}

	private static Predicate checkNCRRegionPerson() {
		return (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
				|| p.getLocation().equalsIgnoreCase("Noida")
				|| p.getLocation().equalsIgnoreCase("Gurgaon");
	}

	private static Predicate checkMale() {
		return (p) -> p.getGender() == SEX.MALE;
	}

	private static Predicate checkRegion(String location) {
		return (p) -> p.getLocation().equalsIgnoreCase(location);
	}

	private static Predicate checkFemale() {
		return (p) -> p.getGender() == SEX.FEMALE;
	}

	public static  Collection process(Collection collection, Predicate predicate) {
		return collection.stream().filter(predicate).collect(Collectors. toList());
	}

}


Person.Java


public class Person {

	public enum SEX {
		MALE, FEMALE
	}

	private long id;
	private String name;
	private int age;
	private SEX gender;
	private String location;
        // Constructor here
        // Getter && Setter ....

Output :

############ Get All Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Female ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]
############ Get All Junior Person who is living in NCR Region ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Male ##############
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
############ Get All Delhi Regional Senior Person ##############
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Female ##############
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Male ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]

Difference between List, List<E>, List<Object>, and List<?> in java

Posted on

java-logoThis is very important topics in Generic to know the difference between List, List<?>,  List<E>, and List<Object>. Enabling Generic in you application code provides you a flexibility of code to work on different type of Data type and ensure to Type safety and easy to read.

In this example, we took a Collection Type i.e List but it can be any Collection Type i.e Set, LinkedList  and Map.

 

List

It’s a raw type and not type safe. It will generate a Runtime exception when casting is bad.


                List list = new ArrayList();
		list.add("Hello");
		list.add(234);
		list.add(new Object());
		// explicitly cast require here
		String s = (String) list.get(0);

 

List<E>

It’s a parameterized type and ‘E‘ can be referred to any non-primitive type, any class type, any interface type, any array type, or even another type variable.


public <E> List<E> unmodifiableList(List<E> list) {
  Collections.unmodifiableList(list);
  return list;
 }

E i.e element can be replaced with some concrete type like String,Integer,Number and other class, interface type.

List<Object>

It is a parameterized type of Object and It’s only allowed to add Object sub-type But does not allow to assign the sub-type reference into that list- means List<Object> instance will not accept the references of List<String> because List<String> is not a subtype of List<Object>, therefore compile generate a compiler errors.


List<Object> listOfObject = new ArrayList<Object>();
listOfObject.add("Hello");
listOfObject.add(234);
// OK
Object o = listOfObject.get(0);

List<String> listOfString = new ArrayList<String>();
listOfString.add("Hi");
//Error :- Type mismatch: cannot convert from List<String> to List<Object>
listOfObject = listOfString; // Compiler time error - Bad casting
List<Object> list1 = listOfString; // Compiler time error - Bad casting

List<Object> list2 = list1; // OK

List<?>

‘?’ Question marks represented an unknown type. List<?> can be something that we don’t know right now. It’s also considered as READ-ONLY list where no any write operation will be performed only read operation is allowed like iteration over it, sizes of list and etc.

List<?> listOnUnknow = new ArrayList();
listOnUnknow.addAll("hello"); // Error because compiler don't know what type of value is going to store here.

We can do it like this :-


public static void reverse(List<?> list) {
     int size = list.size();
     if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
           swap(list, i, j);
     } else {
    ListIterator fwd = list.listIterator();
    ListIterator rev = list.listIterator(size);
    for (int i=0, mid=list.size()>>1; i<mid; i++) {
    Object tmp = fwd.next();
    fwd.set(rev.previous());
    rev.set(tmp);
}
}
}

Thanks

Difference between JVM, JDK,JRE and JIT

Posted on

java-logo

These are the core concept of Java programming language. Most of Java developer are always confused to link between these concepts. Although these looks similar but they are different from each other and their specification.
However, a JVM comes along with JRE & JDK libraries but JRE,JDK and JVM are dependent on operating system machine but Java is independent. here we will see the difference between these and usages :-

Java Virtual Machine (JVM)

JVM is  an abstract machine and subsystem of JDK & JRE. A java program execution uses a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that is, virtual and doesn’t really exist. This so-called “virtual” computer is known as the Java virtual machine (JVM). The machine language for the Java virtual machine is called Java bytecode.
Java Virtual Machine is a program that runs pre-compiled Java programs, which mean JVM executes .class files (byte code) and produces output. The JVM is written for each platform supported by Java included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language. There are many JVM implementations developed by different organizations i.e IBM

The JVM performs following main tasks:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

 

main-qimg-fa65b143171397549e5169a2f7167cc5

 

Java Development Kit (JDK)

JDK stands Java Development Kit, it includes the JRE, set of API classes, Java compiler, Webstart and additional files needed to write Java applets and applications.  So final conclusion is it content every file which useful in developing an application whether it standalone or web based.

Java Development Kit is a bundle of the following software components that are needed to develop Java based applications.

main-qimg-3d375760a6564a7b34c5936dfd66a814

Java Runtime Environment (JRE)

JRE provides Java Runtime environment to run an applet and Java-related web applications. It is an implementation of the JVM which actually executes Java programs. It includes the JVM, core libraries and other additional components to run applications and applets written in Java. Java Runtime Environment is a must install on a machine in order to execute pre-compiled Java Programs. JRE is smaller than the JDK so it needs less disk space and it is so because JRE does not contain Java compiler and other software tools needed to develop Java programs.

Just in Time Compiler (JIT)

JIT are advanced part of Java Virtual machine (JVM) which is used to optimize byte-codes to machine instruction conversion part by compiling similar byte-codes at the same time and thus reducing overall execution time. JIT is part of Java Virtual Machine and also performs several other optimizations such as inline function.

 

Java 8 – Default Methods

Posted on

Java-8

In my previous posts, we have discussed on Lambda Expressions in Java 8.  In this post we will discuss other cool features of Java 8 is Default methods.

Default methods enable you to add new functionality to the interfaces without breaking the class that implements that interface. It ensures that compatibility with code written for older versions of those interfaces.

A Default method is denoted by a keyword “default” by adding it before function access modifier. Also, an Interface or Functional Interface  can have one or more default methods.

default void method1(){

           // Default method body …..

}

According to “Open and Close” principle, which is also intended to open for extension but closed for modifications is stated that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Prior to Java 8, An interface can contain only abstracts methods and all classes that implement that Interface must be implemented all abstracts methods by the rule if any new functionalities need to be added into existing Interface that all implementor classes should be forced to implement the Interface’s methods. More likely it’s incompatible with code written for older versions of Interface then more efforts need to be required to change across the implementor classes.

By approaching default methods in Java 8, it can be fixed this issue by introducing the default methods in Interface. Default  methods do not force to override in subclasses, It is up to you either you can override or not.

Look at the below snippet code of Default Methods in Java 8.

Default method provides us a fixability to allow a method to be implemented in Interface. so Implementation may be used as default method  if a concrete class does not provide the implementation for that.


interface Calculable {
                // abstract method 
		int calc(int x, int y);
		// default method
		default void method(){
			System.out.println("hello");
		}
	}

In this snippet code example, calc() is an abstract method and method() is a default method which has been given the body. However, in this case,  Calculable is a Functional Interface.

Default methods in Multiple Inheritance :-

Since in Java, We can implement  multiple  inheritance  by using Interface but what happened if two or more Interfaces have  a default method with the  same signature then it’s causing a conflict in methods calls in implementor classes. Look at the below code, We have created two Interface i.e Executor & Runnable that have two methods respectively one is an abstract method and other is a default method that is exactly same as both Interface.

Here, MyClass is implemented both Interface Runnable & Executor then subsequently compiler reported a Compile time error i.e

“Duplicate default methods named getStatus with the parameters () and () are inherited from the types Runnable and Executor.”


package com.excerise1;

interface Executor {

	void execute();

	default void getStatus() {
		System.out.println("Ready to Execute.");
	}

}

interface Runnable {
	void run();

	default void getStatus() {
		System.out.println("Ready to Run.");
	}
}
/*
  COMPILER Errors:- Duplicate default methods named getStatus with the parameters () and () are inherited 
                    from the types Runnable and Executor
 */
public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}
}


In above code, Compiler force to override either one of default methods of Runnable or Executor Interface, Otherwise Compiler will not know what default method to used at a time.

In order to workaround solution, we implement default method in subclass i.e MyClass therefore it’s overriding both methods of Runnable & Executor Interface.


public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getStatus() {
		
	}
}


In the above code, getStatus() methods has a dummpy body or own definitation but if you want to invoke one of either Runnable or Executor default methods then we do it as following ways:-


        @Override
	public void getStatus() {
		Runnable.super.getStatus();
	}
   // OR
	/*@Override
	public void getStatus() {
		Executor.super.getStatus();
	}*/

Thanks
——-

Java 8 – Lambda Expressions

Posted on Updated on

Java-8

What is Lambda Expressions in Java 8 ?

First, it was introduced in Java 8, which is one of most powerful features of Java 8.

Lambda is a functional programming which is a way to passing a block of code to function argument.  JavaScript is one of  the best example of functional programming. A functional programming has evolved to avoid the changing state and mutable data. It is a declarative programming that is done on expression and declarative rather than statements.

Syntax of Lambda Expression:- 

(parameters)-> expression body

  • Lambda expression can have zero,one or more parameters.
  • Type of Lambda parameter can have explicitly declared or depend on the context.
    • ()->System.out.println(“hello how are u”);
    • (username)->System.out.println(“Welcome, “+username+” This is test message”);
    • (x,y)->return (x+y);
    • (int x,inty)->return (x+y);
  • Body of Lambda Expression can contain zero,one and multi line statements.
  • Multi line expression body can be enclosed by curly brackets.

()->{
System.out.println("Hello, This is first statement");
System.out.println("Hello, This is Second statement");
}

Example Of Lambda Expression :-


package com.excerise1;

public class Java8LambdaTest {

	public static void main(String args[]) {

		new Thread(() -> {
			System.out.println(" This is Thread " + Thread.currentThread().getName());
		}).start();

		Runnable runnable = () -> {
			for (int i = 0; i < 5; i++) {
				try {
					System.out.println(
							" This is Thread " + Thread.currentThread().getName() + " with Iteration (" + i + ")");
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}
}

In the above code, Compiler can automically cast Lambda Expression to Runnable so no any casting required.

Output here :-

This is Thread Thread-0
This is Thread Thread-1 with Iteration (0)
This is Thread Thread-1 with Iteration (1)
This is Thread Thread-1 with Iteration (2)
This is Thread Thread-1 with Iteration (3)
This is Thread Thread-1 with Iteration (4)

 

What is Functional Interface?

A functional interface is a interface that has only one abstract method on it. like Runnable interface that has only one methods i.e run(). Each Lambda Expression can be implicitly assigned a interface called Functional Interface.

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

@FunctionalInterface annotation is used to indicate that a Interface type declaration is intended to be a Functional Interface. It can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface.

i.e in the below code, Compiler generated an compile time errors-
Invalid ‘@FunctionalInterface’ annotation; Executable is not a functional interface


@FunctionalInterface
interface Executable{
	void execute();
	void submit();
}
 

Example of Funcational Programming:-


package com.excerise1;

import com.excerise1.Calculator.Calculable;

class Calculator {
	interface Calculable {
		int calc(int x, int y);
	}


	private int number1;
	private int number2;

	public Calculator(int x, int y) {
		this.number1 = x;
		this.number2 = y;
	}

	public int calc(Calculable cal) {
		return cal.calc(number1, number2);
	}

}

public class Java8Test3 {
	public static void main(String args[]) {

		Calculable addition = (a, b) -> (a + b);
		Calculable substraction = (a, b) -> (a < b ? b - a : a - b);
                Calculable multiply = (a, b) -> (a * b);
		Calculable divide = (a, b) -> (a / b);

		Calculator cal = new Calculator(10, 20);
		System.out.println(" Addition Result is :" + cal.calc(addition));
		System.out.println(" Substraction Result is :" + cal.calc(substraction));
		System.out.println(" Multiply Result is :" + cal.calc(multiply));
		System.out.println(" Dividision Result is :" + cal.calc(divide));

	}
}

Output here :-

 Addition Result is :30
Substraction Result is :10
Multiply Result is :200
Dividision Result is :0

Here, Lambda Expression is matched against the parameter of calc() method parameters, if Lambda Expression matches with the parameters of calc() then Lambda expression can turn into a function that implements the same interface as that parameter.