Sunday, March 6, 2016

Enumeration Interface Quick Reference Guide

Enumeration Interface Quick Reference Guide

What is Enumeration?

Enumeration is legacy iteration mechanism implemented in Hashtable, Vector, Dictionary and several other classes. An object that implements the Enumeration interface is eligible to enumerate through the series of elements, one elements at a time. Enumeration is not used frequently. Iterator has replaced Enumerator by providing few advantages like removing elements while iterating and better method names.

Method

Description
boolean hasMoreElements()
Returns true if there are more elements in enumeration.
Returns false if there are no more elements in enumeration.

E nextElement()
Returns the next elements of this enumeration.
Throws exception NoSuchElementException if no element is present in enumeration.


Comparator Interface Quick Reference Guide

Comparator Interface Quick Reference Guide

What is Comparator interface?
               
Comparator interface is used to impose total ordering on collection of objects. Comparator is used when you want to implement your own ordering strategy. Read more about Comparator interface here. Prior to Java 8 Comparator interface had only two methods i.e
compare(T o1, T o2) and equals(Object obj). As of Java 8 several new methods are provided. We will look at them one by one.

Method and Description

1.                int compare(T o1, T o2)

compare method compares two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


2.                boolean equals(Object obj)

Indicates whether some other object is equals to this Comparator.


3.                default Comparator<T> reversed()

Returns a Comparator which imposes reverse ordering of this Comparator.


4.                default Comparator<T> 
                     thenComparing(Comparator<? super T> other)

Returns a lexicographic order Comparator with another Comparator. If this Comparator considers two elements equals i.e. compare(a, b) == 0 then other Comparator is used to determine the order.


5.                default <U> Comparator<T> thenComparing(
                     Function<? super T, ? extends U> keyExtractor,
                     Comparator<? super U> keyComparator)

Returns a lexicographic-order comparator with a Function that extracts a key to be compared with the given Comparator.


6.                default <U extends Comparable<? super U>> Comparator<T> 
                     thenComparing(Function<? super T, ? extends U> keyExtractor)

Returns a lexicographic-order Comparator with a function that returns Comparable sort key.


7.                default Comparator<T> thenComparingInt(
                     ToIntFunction<? super T> keyExtractor)

Returns a lexicographic-order Comparator with a function that extracts a int sort key.


8.                default Comparator<T> thenComparingLong(
                     ToLongFunction<? super T> keyExtractor)

Returns a lexicographic-order Comparator with a function that extracts a long sort key.


9.                default Comparator<T> thenComparingDouble(
                     ToDoubleFunction<? super T> keyExtractor)

Returns a lexicographic-order Comparator with a function that extracts a double sort key.


10.            public static <T extends Comparable<? super T>>
                    Comparator<T> reverseOrder()

Returns a Comparator that imposes the reverse of natural ordering.


11.            public static <T extends Comparable<? super T>>
        Comparator<T> naturalOrder()

Returns a Comparator that imposes the reverse of natural ordering.


12.            public static <T> Comparator<T> nullsFirst(
                     Comparator<? super T> comparator)

Returns a null safe Comparator that considers null to be less than non-null.


13.            public static <T> Comparator<T> nullsLast(
                     Comparator<? super T> comparator)

Returns a null safe Comparator that considers null to be greater than non-null.


14.            public static <T, U> Comparator<T> comparing(
                     Function<? super T, ? extends U> keyExtractor,
                     Comparator<? super U> keyComparator)

Accepts a function that extracts a sort key from a type T and returns Comparator<T> that compares by that sort key using specified Comparator.


15.            public static <T, U extends Comparable<? super U>> Comparator<T>
        comparing(Function<? super T, ? extends U> keyExtractor)

Accepts a function that extracts a Comparable sort key from a type T and returns a Comparator<T> that compares by that sort key.


16.            public static <T> Comparator<T> comparingInt(
                     ToIntFunction<? super T> keyExtractor)

Accepts a function that extracts an int sort key from a type T and returns Comparator<T> that compares by that sort key.


17.            public static <T> Comparator<T> comparingLong(
                     ToLongFunction<? super T> keyExtractor)

Accepts a function that extracts a long sort key from a type T and returns Comparator<T> that compares by that sort key.


18.            public static<T> Comparator<T> comparingDouble(
                     ToDoubleFunction<? super T> keyExtractor)

Accepts a function that extracts a double sort key from a type T and returns Comparator<T> that compares by that sort key.






Saturday, March 5, 2016

Java Iterable Interface Quick Reference Guide

Java Iterable<E> Interface Quick Reference Guide

What is Iterable?
Implementing this interface allows the object to be target of for-each loop. Iterable Interface had only one method prior to Java 8. But as of Java 8, it has 2 additional methods. Collection interface extends Iterable interface so all the Collections are Iterable.

Method
Description


Iterator<T> iterator()
Returns the iterator that iterates over elements of type T.

default void
forEach(Consumer<? super T> action)

forEach is default method. This method performs action on every elements of on target Iterable. The argument Consumer is a Functional Interface. Read about it here.

default Spliterator<T> spliterator()

Creates a Spliterator over the elements described by this Iterable.



Comparable Interface Quick Reference Guide

Comparable Interface Quick Reference Guide

What is Comparable interface?
Comparable Interface is used to impose a total ordering on objects of class that implements it. The ordering is classes natural ordering and the method of Comparable interface i.e. compareTo() is referred as natural comparison method. Note that e1.compareTo(e1) == 0 if and only if e1.equals(e2) == true. Classes like String, Integer, Float, etc implement this interface to impose the natural ordering. Read more about Comparable here.

Method
Description

int compareTo(T o)
Compares this object with specified object.
If x.compareTo(y) == 0 then x.equals(y) == true.
In other words
(x.comapreTo(y) == 0) == (x.equals(y))



ListIterator Interface Quick Reference Guide

ListIterator Interface Quick Reference Guide

What is ListIterator?
ListIterator interface is an advance version of Iterator. ListIterator allows you to iterate or traverse the list in either direction, modify the list during iteration and get current position in list. Read more about ListIterator here.

Method

Description
boolean hasNext()
Returns true if there are more elements while list is being traversed in forward direction.

boolean hasPrevious()
Returns true if there are more elements when list is being traversed backwards.

E previous()
Returns the previous element in iteration while being traversed in backward direction. It will throw NoSuchElementException if there are no more elements.

E next()
Returns the next element in iteration while being traversed in forward direction. It will throw NoSuchElementException if there are no more elements.

int nextIndex()
Returns the index of element that will be returned by next()

int previousIndex()
Returns the index of element that will be returned by previous()

void remove()
removes the element from the list which was returned by next() or previous()

void set(E e)
Replaces the last element that was returned by next() or previous().

void add(E e)
Inserts element e in the list


Iterator Interface Quick Reference Guide

Iterator Interface Quick Reference Guide

What is Iterator?
Iterator interface is used to iterator or step through the Collection. Iterator is used as replacement of Enumeration in Java Collections Framework. As compared to Enumeration interface Iterator allows us to remove elements from underlying Collection. Iterator interface has better names as compared to Enumeration. Iterator interface had 2 methods prior to Java 8. As of Java 8 two default methods: remove() and forEachRemaining() were added making it total of 4 methods. Two are abstract methods and other two methods are default methods.

Method
Description

boolean hasNext()

hasNext() method returns true if there are more elements in iteration. Returns false otherwise.

E next()

next() method returns next element in iteration.

default void remove()


remove() method is used to remove the most recent element returned by this iterator.

default void
forEachRemaining(Consumer<? super E> action)

This method performs action on remaining elements in iteration. The argument Consumer is a Functional Interface. Read about it here.




Friday, March 4, 2016

Stream Introduction Part 2.

Stream Introduction Continued.

In previous post we saw how we used to write imperative code i.e. we are telling HOW to do. We also saw how to write declarative code i.e. we are telling WHAT to do. Declarative code is must more concise and easily understandable.

Let us revise what we did previously.

Below is imperative code that we are used to write.
Get names of Person whose age is greater than 25 sorted by name.
List<Person> qualifiedPeople = new ArrayList<Person>();
      for (final Person person : people) {
            if (person.age() > 25) {
                  qualifiedPeople.add(person);
            }
      }

             Collections.sort(qualifiedPeoplenew Comparator<Person>() {
            @Override
            public int compare(final Person person1,
                               final Person person2) {
                  return person1.name().compareTo(person2.name());
            }
      });

            List<String> personName = new ArrayList<String>();
      for(final Person person: qualifiedPeople){
            personName.add(person.name());
      }

So the above code does the expected. But doesn’t it feel that it is too much hassle to do. In SQL this would be so easy to do.

As of Java 8 we have a better solution. Also we use Declarative programming i.e. se say WHAT we want rather than specifying HOW to do it. Let us look at Java 8 code.
    List<String> p =

     listOfPeople().stream()
                   .filter(person -> person.age() > 25)
                   .sorted(Comparator.comparing(person -> person.name()))
                   .map(person -> person.name())
                   .collect(Collectors.toList());

See the code looks elegant. It is simple to understand and no clutter. In fact, we can actually read the code. List, stream through and filter all person whose age is greater than 25 and sort them by name and put them in a list. Isn’t it awesome?

So using Java 8 we are focusing only on our business logic and avoiding much of boiler plate code.

Business logic involves in database like operations like ordering, filtering, grouping, etc. We see that we implement them again and again with fact that we generate too much of Garbage. In the imperative style programming the List qualifiedPeople is used temporarily and then discarded.

We know that Collections are used heavily in Java application. We store data in it and then process it. How do we process it? Imperatively. We iterate through the Collection and process each and every element in it. Let’s say that we have a large Collection say a million elements.
·       So processing it in serially does not make sense. You have multiple cores on your machine why can’t you leverage it?

The answer to the above question is STREAMS.

Stream can help you chain complicated data processing while keeping your code readable and intent clear.

Look at the below diagram. We provide Lambda operation to filter, sorted, map and collect. This are higher level of building blocks and so they don’t depend on any specific threading models.


                    Figure: Forming a Stream pipeline by chaining Stream Operations. 

Hence their implementation can be single threaded or can be potentially utilize the multicore architecture.

The code becomes expressive with declarative style of code. So essentially stream provide us following:

  1. Declarative style of programming: More concise, more readable and more expressive.
  2. Composability: Assembling the complex behavior by aggregating the simple behavior.
  3. Parallelizable: Parallel programming can potentially lead to improved performance as it can utilize the multiple cores.
  4. Streams are Lazy: Computation is only performed when the terminal operation is initiated.

That’s all for Stream introduction. In next post we will start working with Streams and explore its methods.

Click here for next post Stream-Getting Started.

Ads Inside Post