Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Monday, 19 February 2018

Java 8 - Join Strings Easily


(Download One Minute Java Mobile app for latest updates)

StringJoiner
StringJoiner class of package java.util.StringJoiner is very helpful for joining delimiter seprated string.
It is used to build a characters sequence separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Example


 If we want to create a string of names seperated by ':' and enclosed in '[' ']' braces than we can write   code as below

 StringJoiner sj = new StringJoiner(":", "[", "]"); ----> 1
 sj.add("George");
 sj.add("Sally");
 sj.add("Fred");
 String requiredString = sj.toString();

 If we print 'requiredString' the output will be as below.

 "[George:Sally:Fred]"

 Note : In line 1 of above example delimiter ':' is compulsory parameter and the prefix '[' and sufix ']'   are optional parameters


Static join() of String
Static method join() from String class is very handy for joining strings in collections

Example


 Set stringSet = new HashSet();
 stringSet.add("Sachin");
 stringSet.add("Rahul");
 stringSet.add("Saurav");
 String newString = String.join(",", stringSet);


 If we print 'newString' the output will be as below.
 "Saurav,Rahul,Sachin"


Java 8 Default Method Interface

(Download One Minute Java Mobile App for Latest Updates)

Introduction

Prior to Java SE 8, interfaces were expected to have abstract methods only and the classes implementing the interfaces had to override all those abstract methods. But Java SE 8 has made it possible to hold method definitions in an interface using Default methods.
Default Methods can be used to introduce new functionalities into interfaces without breaking the existing classes which implement those interfaces. The Default methods provide their own definitions, so there is no compulsion on implementing classes to override default methods.

Syntax


  public interface firstDefaultTest
 {
  default void test()
  {
   System.out.println("This is a default method with default keyword");
  }
 }

Things to know

  • A default method cannot override methods from java.lang.Object
  • An interface can also have a static default method from Java 8
  • There are chances that 2 different interfaces may have default method with same name and signature and a class might implement both the interfaces, which causes ambiguity.
    • One way is to override the default method in implementing class
    • Other way is to override default method and invoke default method of the required interface with super keyword ex: interfaceName.super.methodName()
  • Default methods help to remove base implementation classes. The default implementations can be provided in the interface and the implementating classes can choose which one to override.