I am learning Java 8 new features and I came across one situation where I was not able to convince my interviewer how java 8 provide more concise code than older version of java. I have provided an example of Functional Interface and comparator interface that class don't have to implement interface. Using lambda expression we can directly provide implementation of method like below code Example1. I have explained him how number of line reduced using java8.
I have also provided example of Comparator interface that we can directly implement Comparator interface using lambda expression. But He said if we are implementing Comparator interface with some class then I can reuse it while using Lambda expression I have to write logic again and again whenever I what to do sorting. So I didn't know how to explain how java 8 provide concise code because as per his description he was right.
For Stream API we can also sort elements, So why should we use Stream API of Java8 for sorting while collection have method Collections.sort. If I am using Stream API for sorting then I have collect all elements in new List while using Collections.sort will sort existing list then why should we use Stream API? Refer Example 3.
So I was not able to understand how Java8 provide concise code and how stream API is helpful or why should I use Stream API.
I have done some searching on google but I haven't found any satisfactory answers.
//Exaple 1
//Traditional Way
interface SampleInterface {
public void sampleMethod();
}
public class SampleClass implements SampleInterface {
@Override
public void sampleMethod() {
// Implementation Logic
}
}
//Using Lambda expression and Functional Interface
@FunctionalInterface
interface SampleInterface {
public void sampleMethod();
}
public class SampleClass {
public static void main(String[] args) {
SampleInterface sf = () -> {System.out.println("Implementation of interface method");};
}
}
//Example 2
Comparator<Student> c = (s1, s2) -> {return (s1.age < s2.age ? -1 : (s1.age > s2.age) ? 1 : 0 );};
//Example 3
//Using Stream API
List<Employee> newList = empList.stream().sorted((v1, v2) -> (v2.id < v1.id) ? -1 : (v2.id > v1.id) ? 1 : 0).collect(Collectors.toList());
//Using comparator
Collections.sort(list, comparator);
Comparator.comparing(Student::getAge)and the like...