Showing posts with label Join. Show all posts
Showing posts with label Join. 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"


Difference Between Yield() and Join()

(Download One Minute Java Mobile app for latest updates)

What is Yeild() in java?

When a thread executes a java.lang.Thread.yield(), the executing thread is suspended and the CPU is given to some other runnable thread. This thread will be in runnable state until the CPU becomes available again.

In other words, the executing thread is put back into the ready queue i.e in runnable state of the processor and waits for its next turn.

Yield method causes the currently executing thread object to temporarily pause and allow other threads to execute. However there is no guarantee that current thread will pause immediately.
Point to note here is, Yield is a static method of Thread class.

Yeild Example


  public class YieldExample
 {
    public static void main(String[] args)
    {
      Thread t1 = new Thread1();
      Thread t2 = new Thread2();
      t1.start();
      t2.start();
   }
  }

 class Thread1 extends Thread
 {
    public void run()
    {
      for (int i = 0; i < 3; i++)
      {
       System.out.println( i + " Iteration of " + "Thread1 is yielding control to Thread2 " );
        Thread.yield();
        System.out.println( i + " Iteration of " + "Thread1 is continuing after Thread2 ");
       }
    }
  }

 class Thread2 extends Thread
 {
    public void run()
    {
      for (int i = 0; i < 3; i++)
      {
       System.out.println( i + " Iteration of " + "Thread2 is yielding control to Thread1 " );
        Thread.yield();
        System.out.println( i + " Iteration of " + "Thread2 is continuing after Thread1 ");
       }
    }
  }


Output


  0 Iteration of Thread1 is yielding control to Thread2
  0 Iteration of Thread2 is yielding control to Thread1
  0 Iteration of Thread1 is continuing after Thread2
  0 Iteration of Thread2 is continuing after Thread1
  1 Iteration of Thread2 is yielding control to Thread1
  1 Iteration of Thread1 is yielding control to Thread2
  1 Iteration of Thread2 is continuing after Thread1
  1 Iteration of Thread1 is continuing after Thread2
  2 Iteration of Thread2 is yielding control to Thread1
  2 Iteration of Thread2 is continuing after Thread1
  2 Iteration of Thread1 is yielding control to Thread2
  2 Iteration of Thread1 is continuing after Thread2


What is Join() in java?

java.lang.Thread class has the join() method which allows one thread to stop execution until another thread completes its execution. In other words, the currently running threads stop executing until the thread it joins with, completes its task.

Variants of join method

Join() : Current thread will wait until the joined thread is dead.
Join(long milliseconds) : Current thread will wait until the joined thread is dead or for specified milliseconds whichever is earlier.
Join (long millis, int nanos) : Current thread will wait until the joined thread is dead or for specified milliseconds + nanos whichever is earlier.

Join Example


 public class JoinExample implements Runnable
 {
  Thread t;
  JoinExample(String threadName)
  {
   t = Thread.currentThread();
   t.setName(threadName);
  }
  public void run()
  {
   if(t.isAlive())
   {
    System.out.println(t.getName() + " is running...");
    System.out.println(t.getName() + " is complete...");
   }
  }
  public static void main(String args[]) throws Exception
  {
   System.out.println("Main Thread started...");
   Thread t = new Thread(new JoinExample("DemoThread"));
   t.start();
   System.out.println("Main Thread paused...");
   // current thread i.e main thread waits for DemoThread to complete
   t.join();
   System.out.print("Main Thread started again...");
  }
 }

Output


  Main Thread started...
  Main Thread paused...
  DemoThread is running...
  DemoThread is complete...
  Main Thread started again...


Comparison

Yeild() Join()
Current thread gives chance to other threads that have equal priority in the Thread-pool. Current thread will pause execution till another thread complete its excution
Current thread goes into runnable state Current thread goes into wait state till other thread is dead
yield() is a static method of thread class Join is not a static method of thread class