Friday, November 18, 2016

Using Lambda Expressions to sort a collection in Java 8

Below is an example to show how to use Lambda expression to sort a collection.

Prior to Java 8, it was necessary to implement the java.util.Comparator interface with an anonymous (or named) class when sorting a collection:
Java SE 1.2
Collections.sort(
    personList,
    new Comparator<Person>() {
        public int compare(Person p1, Person p2){
            return p1.getFirstName().compareTo(p2.getFirstName());
        }
    }
);
Starting with Java 8, the anonymous class can be replaced with a lambda expression. Note that the types for the parameters p1 and p2 can be left out, as the compiler will infer them automatically:
Collections.sort(
    personList, 
    (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName())
);
The example can be simplified by using Comparator.comparing and method references expressed using the :: (double colon) symbol.
Collections.sort(
    personList,
    Comparator.comparing(Person::getFirstName)
);
A static import allows us to express this more concisely, but it is debatable whether this improves overall readability:
import static java.util.Collections.sort;
import static java.util.Comparator.comparing;
//...
sort(personList, comparing(Person::getFirstName));
Comparators built this way can also be chained together. For example, after comparing people by their first name, if there are people with the same first name, the thenComparing method with also compare by last name:
sort(personList, comparing(Person::getFirstName).thenComparing(Person::getLastName));

Thursday, September 15, 2016

Scheduling a Job using spring

Requirement:

We have to send email on a regular interval by checking a condition automatically.

Solution:
We can use Queartz Job scheduler which is an open source job scheduling library and can be attached with any java application.

Alternatively we can use Spring's Task scheduler using TaskScheduler and TaskExecutor.

Pros:

  • This approach is good for the situation where you are already using Spring in code. 
  • Its quick and easy to implement.
  • You do not have many jobs to run.


To implement the spring way we should use @EnableScheduling annotation in our AppConfig.java
The above annotation enables Spring's scheduled task execution capability.

Below is an example which gets executed every hours and prints the current time.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package blogspot.thinkwithjava;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 *
 * @author R.D
 *
 */
@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "0 0 0/1 1/1 * ?")
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}


cron = "0 0 0/1 1/1 * ?"

To schedule a task we provide a cron pattern as mentioned above. The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.

Cron pattern for every Five Minute

"0 0/5 * 1/1 * ?"

Cron pattern for every hour

 "0 0 0/1 1/1 * ?"

Cron pattern for every four hour

"0 0 0/4 1/1 * ?"

More information is given here.

Tuesday, September 13, 2016

Remove duplicate character from a given string

This is one of the tricky question asked in the interviews. Not only to check logical ability of candidates but to check their understanding about algorithms and complexities.

So here is the Problem statement:

 How to remove duplicate characters from String in Java? For example, if given String is "aaaaaa" then output should be "a", because rest of  the "a" are duplicates. Similarly, if the input is "abcd" then output should also be "abcd"  because there is no duplicate character in this String.

Algorithm:


 This algorithm goes through each character of String to check if its a duplicate of already found character. It skip the duplicate character by inserting 0, which is later used to filter those characters and update the non-duplicate character. 
Time Complexity of this solution is O(n^2), excluded to UniqueString() method, which creates String from character array. 

This method will work even if String contains more than one duplicate character.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * * Java Program to remove duplicate characters from String.
 * 
 * @author Ram.Dutt
 */
public class RemoveDuplicateChar {
 public static void main(String args[]) {
  
  
 String[] testdata = { "aabaaaaascs", "abcd", "aaaa", null, "", "aaabbb", "abababa" };
 for (String input : testdata) {
 System.out.printf("Input : %s Output: %s %n", input, removeDuplicates(input));
 }
 System.out.println("Calling removeDuplicatesFromString(String str).");
 for (String input : testdata) {
 System.out.printf("Input : %s Output: %s %n", input, removeDuplicatesFromString(input));
 }
}

 
 public static String removeDuplicates(String word) {
  if (word == null || word.length() &lt; 2) {
   return word;
  }
  int pos = 1;
  // possible position of duplicate character
  char[] characters = word.toCharArray();
  for (int i = 1; i &lt; word.length(); i++) {
   int j;
   for (j = 0; j &lt; pos; ++j) {
    if (characters[i] == characters[j]) {
     break;
    }
   }
   if (j == pos) {
    characters[pos] = characters[i];
    ++pos;
   } else {
    characters[pos] = 0;
    ++pos;
   }
  }
  return toUniqueString(characters);
 }

 /*
  * * This solution assumes that given input String only contains * ASCII
  * characters. You should ask this question to your Interviewer, * if he
  * says ASCII then this solution is Ok. This Algorithm * uses additional
  * memory of constant size.
  */

 public static String removeDuplicatesFromString(String input) {
  if (input == null || input.length() &lt; 2) {
   return input;
  }
  boolean[] ASCII = new boolean[256];
  char[] characters = input.toCharArray();
  ASCII[input.charAt(0)] = true;
  int dupIndex = 1;
  for (int i = 1; i &lt; input.length(); i++) {
   if (!ASCII[input.charAt(i)]) {
    characters[dupIndex] = characters[i];
    ++dupIndex;
    ASCII[characters[i]] = true;
   } else {
    characters[dupIndex] = 0;
    ++dupIndex;
   }
  }
  return toUniqueString(characters);
 }

 /*
  * * Utility method to convert Character array to String, omitting * NUL
  * character, ASCII value 0.
  */ public static String toUniqueString(char[] letters) {
  StringBuilder sb = new StringBuilder(letters.length);
  for (char c : letters) {
   if (c != 0) {
    sb.append(c);
   }
  }
  return sb.toString();
 }
}

That is it. You can use different logic too to remove duplicate values from the array in Java as well.

Happy reading!

Friday, September 2, 2016

String pool differences in java 6 and java 7

While reading a blog here, I found a quite interesting improvements in String Pool


  • String pool is relocated to Java heap space from PermGen space.
  • The default size of String pool is increased to 600013 entries from 1009 in Java 6.
  • The -XX:StringTableSize JVM option is provided to specify the size of String pool. 

  • Monday, August 22, 2016

    What is Phishing



    About Phishing Phising is an online attempt to trick a user by pretending to be an official login page or an official email from an organization that you would have an account with, such as a bank or an email provider, in order to obtain a user’s login and account information. In the case of a phishing login page, the login page may look identical to the login page you would normally go to, but the website does not belong to the organization you have an account with (the URL web address of the website should reflect this). In the case of a phishing email, the email may look like an email you would get from the organization you have an account with and get emails from, but the link in the email that it directs you to takes you to the above phishing login page, rather than a legitimate login page for that organization.

    To prevent your account information from being obtained in a phishing scheme, only log in to legitimate pages of the websites you have an account with. For example, "www.facebook.example.com" is not a legitimate Facebook page on the "www.facebook.com" domain, but "www.facebook.com/example" is a legitimate Facebook page because it has the "facebook.com" domain. When in doubt, you can always just type in "facebook.com" into your browser to return to the legitimate Facebook site.


    Never click suspicious links: It is possible that your friends could unwillingly send spam, viruses, or malware through Facebook if their accounts are infected. Do not click this material and do not run any ".exe" files on your computer without knowing what they are. Also, be sure to use the most current version of your browser as they contain important security warnings and protection features. Current versions of Firefox and Internet Explorer warn you if you have navigated to a suspected phishing site, and we recommend that you upgrade your browser to the most current version. You can also find more information about phishing and how to avoid it at http://www.antiphishing.org/consumer_recs.html and http://onguardonline.gov/phishing.html.

    Tuesday, August 16, 2016

    How to convert date into datetime in java

    Java 8 has adopted Jodatime in Jave SE8. Joda time is now introduced in java.time package.

    Joda time was de facto standard date and time library prior to Java SE8.

     Following are the ways to convert the java util dates with java.time.* and vice-versa.

    The idle way (for all these conversions) is to convert to Instant. This can be converted to LocalDateTime by telling the system which timezone to use. This needs to be the system default locale, otherwise the time will change.

    Convert java.util.Date to java.time.LocalDateTime


    Date ts = new Date();
    Instant instant = Instant.ofEpochMilli(ts.getTime());

    LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());


    Convert java.util.Date to java.time.LocalDate

    Date date = new Date();
    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDate res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();

    Convert java.util.Date to java.time.LocalTime

    Date time = new Date();
    Instant instant = Instant.ofEpochMilli(time.getTime());
    LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();

    Convert java.time.LocalDateTime to java.util.Date

    LocalDateTime ldt = LocalDateTime.now();
    Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
    Date res = Date.from(instant);

    Convert java.time.LocalDate to java.util.Date

    LocalDate ld =  LocalDate.now();

    Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
    Date res = Date.from(instant);

    Convert java.time.LocalTime to java.util.Date

    LocalTime lt = LocalTime.now();
    Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
            atZone(ZoneId.systemDefault()).toInstant();

    Date time = Date.from(instant);

    A list of key features provided at joda-time official website:

    A selection of key features:
    • LocalDate - date without time
    • LocalTime - time without date
    • Instant - an instantaneous point on the time-line
    • DateTime - full date and time with time-zone
    • DateTimeZone - a better time-zone
    • Duration and Period - amounts of time
    • Interval - the time between two instants

    Tuesday, March 15, 2016

    What is DevOps?

    What is DevOps?

    In a software industry we do have 2 teams working together to build and deliver a product. Development and Operation teams.
    So before we understand the DevOps we should know a bit more about these 2 teams and their interoperability.

    Development team is responsible for adding new features in software. So the nature is keep changing!
    Operation team is responsible for keeping the system stable and running. Here the nature is do not change at all because of the element of fear to become unstable after changes.

    So both of these are teams functions opposite in nature but though work together.

    Why we should use it?

    As we saw above that the 2 teams are opposite in nature though they work together. Hence they do not work efficiently, affecting the productivity of the projects.

    So overcome this here comes in DevOps.

    The formal definition of DevOps could be:

    DEVOPS IS THE UNION OF PEOPLE, PROCESS AND PRODUCTS TO ENABLE CONTINUOUS DELIVERY OF VALUE TO OUR END USERS.

    How it differ from the traditional ways?

    The punchline of DevOps is - 'you build it, you run it'.

    Prior to DevOps


    A developer got a bunch of tasks and he finished his tasks in a given timeline and then the Quality assurance(QA) teams comes into picture. They do a lot of functional testing, manual testing, regression testing, User acceptance testing and so on to validate those changes.

    Now after verification and validation the changes handed over to operation teams to get it deployed correctly on the different environments.

    And here the most challenging phase of a product starts. The development team don't understand about operations and operation team don't understand the affect of changes done in the product. ultimately we ran through a situation where all teams start playing a  blam game and we loose the most valuable things i.e. TIME.

    After DevOps


    DevOps says do not segregate the teams that don't understand each other. Rather develop a team which has both of these skills.

    Now the DevOps teams should be equipped with some tools and techniques.
    We will see few tools that I am using right now in my next blog.

    Thanks for reading. Keep sharing the feedbacks.



    Java garbage collection

    In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...