Java Topics
Java Topics
1.Comparable Interface :
The class must implement Comparable Interface to sort its instances/objects.
This interface is used for natural ordering of objects.
Sorting achieved by using compareTo method which accepts one parameter that specifies the class
instance.
public int compareTo(T o);
Above method is invoked when Collections.sort(someList); is called.
The compareTo method returns negative,zero or positive integer if the current object is less
than,equal to or greater than the specified object respectively.
The compareTo method throws NullPointer exception if the object passed is null.
It may throw a ClassCastException if the specified object's type prevents it from being compared to
current object.
2. Comparator Interface:
The class must implement Comparator Interface to sort based on any custom order.
Used for custom ordering of objects.
Uses compare(T o1,T o2) method to achieve sorting of objects.
This is a functional interface with only a "Single Abstract Method" (compareTo).
Hence lambda expressions can be used if you are using java 8.
In Java 8, the List interface is supports the sort method directly, no need to
use Collections.sort anymore.
Functional Interface: A functional interface is an interface that contains only one abstract method.
They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be
used to represent the instance of a functional interface.
Before Java 8, we had to create anonymous inner class objects or implement these interfaces.
Anonymous Inner Class: It is an inner class without a name and for which only a single object is
created.
@Override
public void run() {
System.out.println("Inside Run");
}
}).start();
In the above code, after compilation, ClassName$1.class is created which represents the
anonymous inner class.
With introduction of lambdas in Java8, anonymous inner classes are no longer created. The code
with lambda below:
Streams:
Stream represents a sequence of objects from a source, which supports aggregate operations.
With Java8, Collection interface has two methods to generate a stream.
stream() - Returns a sequential stream considering collection as its source.
parallelStream() - Returns a parallel Stream considering collection as its source.
Parallel streams divide the provided task into many and run them in different threads, utilizing
multiple cores of the computer. On the other hand sequential streams work just like for-loop using
a single core.
list.stream().sorted(Comparator.reverseOrder()).collect(Collectors
.toList()) -> returns the natural ordering sorted in descending
order.
users.stream.sorted(Comparator.comparingInt(User::getAge)).collect
(Collectors.toList()) -> sorts based on user age in ascending
order.
users.stream.sorted(Comparator.comparingInt(User::getAge).reversed
()).collect(Collectors.toList()) -> sorts based on user age in
descending order.