Saturday, August 22, 2015

ArrayList class Constructors

ArrayList class Constructors

In previous post we saw the introduction on ArrayList class and how it is different from arrays. We also saw List interface and some details of ArrayList class.

In this post we will learn about 3 different types of constructors provided in ArrayList class.
1.       No-args constructor – This constructor is used to create a default list of size 10.
2.       Initial Capacity as argument – This constructor takes int as argument which specifies     initial capacity of list.
3.       Collection as argument – This constructor constructs an ArrayList from the specified       Collection provided as argument.

Above is the gist now let us see how to write these constructors, add some elements into it and print it out.

1.       No-args constructor – As we just saw this constructor creates a default list with size       10. Below is the code uses default constructor and added few elements of type String      into it.
   /**
    * ArrayList<> class has a no-args constructor.
    * This constructor creates an empty list with
    * initial capacity as 10.
    * */
   public static void arraylistContructorNoArgs() {
          List<String> names = new ArrayList<String>();
          names.add("Ned");
          names.add("Catelyn");
          names.add("Rob");
          names.add("Arya");
          names.add("Sansa");
          System.out.println(names);
   }
/**
               * Output
               * [Ned, Catelyn, Rob, Arya, Sansa]
     * */

2.       Initial Capacity as Argument – In this type of constructor we give an int value to             constructor and it creates the list of that size.
/**
    * ArrayList<> class has a constructor that takes int as argument.
    * argument acts as initial capacity of ArrayList.
    * This constructor creates an empty list with
    * initial capacity as 10.
    * */
   public static void arraylistConstructorInitialCapacity() {
          List<String> names = new ArrayList<String>(20);
          names.add("Ned");
          names.add("Catelyn");
          names.add("Rob");
          System.out.println(names);
   }
/**
    * Output
    * [Ned, Catelyn, Rob]
    * */

3.       Collection as argument – This constructor creates a list of Collection, in an order             elements are returned by the Collection.
       /**
        * ArrayList<> class has a constructor that accepts 
        * Collection as argument.
        * */
       public static void arraylistConstructorCollectionArgs() {
              List<String> days = new ArrayList<String>();
              days.add("Monday");
              days.add("Tuesday");
              days.add("Wednesday");
              List<String> names = new ArrayList<String>(days);
              names.add("Ned");
              names.add("Sansa");
              System.out.println(names);
       }
       /**
        * Output
        * [Monday, Tuesday, Wednesday, Ned, Sansa]
        * */

So that’s all on 3 constructors of ArrayList. In next post we will see 2 add() methods of ArrayList class.


ArrayList class Introduction (and how it is different from Array)

ArrayList class (and how it is different from Array).

Before we begin with the tutorial I would like to cite that ArrayList class comes under Java Collections Framework. I would highly recommend you to read about Java Collections Framework, its interfaces and Collection interface.

ArrayList class implements the List interface (List Interface extends Collection Interface and Collection Interface extends Iterable Interface) and extends AbstractList class.

ArrayList class uses Object[] array to store elements of type E. Type E means elements of any type. As ArrayList uses Object[] array to store elements we can say ArrayList is backed by array. But do not confuse that ArrayList and array are same.

There are several differences between ArrayList and array but the most important one is that ArrayList are polymorphic in nature whereas

There are several differences between ArrayList and array. I have written different post on it. I would highly recommend you to read it. Click here to read it. It is also one of the Java Collection Interview Question.

If you have made it to this line then I can assume that you now know what difference between ArrayList and array is.

In next post we will see how to create object of ArrayList class which can be done in 3 ways. No_Args constructor, initial capacity constructor and construct ArrayList from Collection.


GOTO to Next Post click here.

Saturday, August 15, 2015

Constructor References

Constructor References

In previous post we saw Method References. In this post we will see Constructor References.

We can create Constructor Reference using ClassName and new keyword as ClassName::new. This fits for the no-args constructor.

  • We can use Supplier Functional Interface for creating an object of Person class.


      Supplier<Person> p = Person::new;
      Person personp.get();

         The above piece of code is equivalent to:

      Supplier<Person> p = () -> new Person();
      Person person = p.get();



  • Let us now try for different examples with different parameters.

          Let us see how to use Constructor Reference when we have parameter to constructor.

Function<String, Person> p = Person::new;
      Person person = p.apply("John Doe");

          Let see Lambda Operator for same.
      Function<String, Person> p = (name) -> new Person(name);
      Person person = p.apply("John Doe");


    So Function's get method will return new instance of Person with name.



  • Now, let us say that you want to create multiple instance of Person with name as parameter. We can leverage the concept of Function interface.

          public class App {

               public static void main(String[] args) {

                      List<String> names = new ArrayList<>(Arrays.asList("Harry", "John",
                        "Kip", "Gunther"));
                      List<Person> person = nameMapper(names, Person::new);
                      System.out.println(person);
                }

                public static List<Person> nameMapper(List<String> names, Function<String, Person> func) {

                      List<Person> person = new ArrayList<Person>();
                      for (String name : names) {
                            person.add(func.apply(name));
                      }
                      return person;
                }
          }



  • Now one step ahead. Let’s say you have 2 parameters for Person constructor as Name and Age. Here, we can leverage the concept of BiFunction interface.

      BiFunction<Integer, String, Person> p = Person::new;
      Person person = p.apply(23, "John Doe");

          Lambda equivalent would be as below:

      BiFunction<Integer, String, Person> p = (age, name) -> new Person(age, name);
      Person person = p.apply(23, "John Doe");


That’s all on Constructor Reference. Read about Method references, Lambda Operator and 43 different Functional Interfaces.


Method References

Method References

Lambda expressions are used to create anonymous methods. But sometimes, lambda just calls an existing method.

Let us take example of it.
·         We will create an anonymous function for filtering null values from List of String.
·         If String is NOT NULL then we will convert it to uppercase and print it.

      public static List<String> populateNames(){
            String[] nameArr = { "Harry", null, "Sansa", "Ned", null, "Roose",
                        "Walder", "Jaqen", null, "Joffery", "Robert", null,
                        "Catleyn", "Peter", "Jack", null, "George", "Martin",
                        "Frey", "Brandon" };
           
            List<String> names=new ArrayList<String>(Arrays.asList(nameArr));
            return names;
      }
     
      public static void toUpperCaseString(List<String> names){
           
              names.stream()
                   .filter(name -> name!=null)
                   .map(str -> str.toUpperCase())
                   .forEach(str -> System.out.println(str));
      }

Now the anonymous function is the Predicate in filter method. This is filter(name -> name!=null) anonymous function.

Now we will convert that filtered value to upper case. This is map(str -> str.toUpperCase()) is calling an existing method.

So when we call the String class’s toUpperCase() method we are  just calling an existing method. There is no problem with telling “How to call the method” rather than calling method just by name. So we can replace lambda in map(..).

So map(str -> str.toUpperCase()) becomes  map(String::toUpperCase) as method reference.

Let us take a different example for Integer sort using method reference.

      public static void intsSort(){
            int[] age = { 16, 22, 22, 25, 24, 16, 23, 19, 19, 27, 20, 20, 12, 13, 18, 15, 20, 26, 29, 22 };
            List<Integer> list=new ArrayList<Integer>();
            for (int i = 0; i < age.length; i++) {
                  list.add(age[i]);
            }
            System.out.println("Before Sort "+list);
            list.sort(Integer::compare);
            System.out.println("After Sort "+list);
      }

Output:
Before Sort [16, 22, 22, 25, 24, 16, 23, 19, 19, 27, 20, 20, 12, 13, 18, 15, 20, 26, 29, 22]
After Sort [12, 13, 15, 16, 16, 18, 19, 19, 20, 20, 20, 22, 22, 22, 23, 24, 25, 26, 27, 29]

Let us now see how to create method references.

Lambda
(args) -> ClassName.staticMethod(args)
Method Reference
ClassName::staticMethod

Lambda
(arg0, args) ->arg0.instanceMethod(args)
Method Reference
ClassName::instanceMethod

Lambda
args() -> instance.instanceMethod(args)
Method Reference
instance::instanceMethod


That’s all on Method References. We will look into them again once we start with Stream API of Java 8.

Read about Constructor References, Lambda Operator and 43 different Functional Interfaces.

Next Post:: Constructor References

Monday, August 10, 2015

Collections class frequency() method

Collections class frequency() method

In this post we will see the frequency() method defined in Collections class. Previously we had studied methods like swap(..), synchronized, binarySearch(..), copy(..), fill(..) , addAll(..), min() with Comparable, min() with Comparator, max() with Comparable, max() with Comparator methods.

I have also written about the Comparable and Comparator Interfaces and differences between them. I would highly recommend that you read those posts.

frequency() method is used to count the specified Object in Collection. As the frequency() method accepts parameter as Collection, so we can pass any type of Collection as parameter to frequency() method.

Below is the code of frequency() method in Collections class. Comments are inserted for understanding the method.

/**
       * Returns number of times the Object o occurs in specified Collection.
       * The equality depends on Object passed as parameter.
       * More specifically if o==null ? e==null : o.equals(e)
       * */
      public static int frequency(Collection<?> c, Object o) {
            //Initialize result to 0.
        int result = 0;
             /**
         * If specified parameter is null check for null elements
              * */
        if (o == null) {
                  for (Object e : c)
                       if (e == null)
                           result++;
             }
            /**
            * If element is not null then check comparison based on equals
            * more specifically o.equals(e)
            * */
            else {
                for (Object e : c)
               if (o.equals(e))
                         result++;
            }
            return result;
      }

Let us built a List of days.

List<String> names=new ArrayList<String>();
            names.add("Monday");
            names.add("Tuesday");
            names.add("Wednesday");
            names.add("Monday");
            names.add("Tuesday");
            names.add("Monday");
            int result=count(names, "Monday");
            System.out.println(result); //Outputs 3

Now, let us write count method with two arguments as List and day.
     
public static int count(final List<String> days, final String day){
            return Collections.frequency(days, day); //returns 3
      }

That’s all on frequency() method of Collections class.


Thursday, August 6, 2015

Behavior Parameterization Part 2

Behavior Parameterization

In previous post we saw how to cope up with requirement change and wrote a code that is worse. So now we will introduce a concept that will help us in coping with requirement change and will get rid of boilerplate code.

In case you are wondering what is boilerplate code – they are lines of code that does not add anything to business logic. Example: for loop.  Who cares about for loop unless you are returning the proper values to client?

Now let us think of better solution of the problem i.e. to get apples of specified color and get apples of specified weight. Notice there is one thing in common in both of requirements i.e. decision is made i.e. boolean value is returned.

Predicate –
Predicate as we know it is a Boolean-valued function in mathematical logic.
Predicate P: X→ {true, false} is called predicate on X.


Let us write Predicate for Apple with a method test. So let us extract an interface with test() method in ApplePredicate Interface.

ApplePredicate Interface

public interface ApplePredicate {
      boolean test(Apple apple);
}


Now let us implement this interface in AppleWeightPredicate class.

public class AppleWeightPredicate implements ApplePredicate {

      @Override
      public boolean test(Apple apple) {
            return apple.getWeight() > 50;
      }
}


Now let us implement this interface in AppleColorPredicate class.

public class AppleColorPredicate implements ApplePredicate {

      @Override
      public boolean test(Apple apple) {
            return apple.getColor().equalsIgnoreCase("green");
      }
}

Now we will write the filter method with List<Apple> and ApplePredicate as parameter. As ApplePredicate is implemented by AppleWeightPredicate and AppleColorPredicate we can pass any instance of those classes. This leads to different behavior. So we are actually passing a behavior as a parameter.

      public static List<Apple> filter(final List<Apple> apples
                                       final ApplePredicate predicate) {

            List<Apple> result=new ArrayList<Apple>();
            for (Apple apple : apples) {
                 
                  if(predicate.test(apple)){
                        result.add(apple);
                  }
            }
            return result;
      }


This method can be called as:
filter(apples, new AppleColorPredicate());
      filter(apples, new AppleWeightPredicate());

Now let us combine AppleColorPredicate and AppleWeightPredicate class as AppleWeightAndColorPredicate class(apple weight greater than 50 and color must be green).

public class AppleWeightAndColorPredicate implements ApplePredicate {

      public boolean test(Apple apple) {

            return apple.getWeight() > 50
                        &&                                                              apple.getColor().equalsIgnoreCase("green");
      }
}


Excellent we just came up with good solution. But there is still a problem of boilerplate code. Bold denotes the boilerplate code. This code does not add anything in our business logic but we have to write it.

Does anonymous inner class solve our problem? Let’s see.

List<Apple> result = filter(list, new ApplePredicate() {
            @Override
            public boolean test(Apple apple) {
                  return apple.getColor().equalsIgnoreCase("green");
            }
      });
So did the anonymous inner class solve your problem? I don’t think so. It just increased it by some weird syntax.

So what is the solution to this? First, I will throw a Java 8 lambda operator “->” here.

List<Apple> greenApples
                        filter(list
                                (Apple apple) -> apple.getColor()
                                                      .equals("green"));

What does this do? So this means that filter out apples with color green. We can use this Lambda Operator if the interface is Functional Interface. To read about Functional Interface click here and here and here.

Now let us change our Predicate interface for generic type T.

public interface Predicate<T> {

      boolean test(T t);
}


Let us change our filter method too for using generic type T.

      public static <T> List<T> filter(final List<T> list,
                  final Predicate<T> predicate) {

            List<T> result = new ArrayList<T>();
            for (T element : list) {

                  if (predicate.test(element)) {
                        result.add(element);
                  }
            }
            return result;
      }

      List<Apple> greenApples 
                        filter(list
                                (Apple apple) -> apple.getColor()
                                                      .equals("green"));
     
      List<Apple> redApples 
                        filter(list
                                (Apple apple) -> apple.getColor()
                                                      .equals("red"));
     
      List<Apple> appleWeight
                     filter(list, (Apple apple) -> apple.getWeight() > 50);
                       
      List<Integer> evenNumbers = filter(ints, (i) -> i % 2 == 0);

See how we passed behavior in the method parameter rather than writing lot of code in a class and then passing instance of the class.


So this is Behavior Parameterization.

Ads Inside Post