A code review guide and checklist when working with Java and related technologies. The following should really help when writing new code in Java applications after upgrading to Java 8 or refactoring code that is < Java8
Instead of
Runnable runner = new Runnable(){
public void run(){
System.out.println("I am running");
}
};
do...
Runnable running = () -> {
System.out.println("I am running");
};
Instead of
public class MyClass implements InterfaceA {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
@Override
public void saySomething() {
System.out.println("Hello World");
}
}
interface InterfaceA {
public void saySomething();
}
Use default methods. Make sure you do not do this as a a habit because this pattern pollutes interfaces.
public class MyClass implements InterfaceA {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
@Override
public void saySomething() {
System.out.println("Hello World");
}
}
interface InterfaceA {
public void saySomething();
default public void sayHi() {
System.out.println("Hi");
}
}
private static void printNames(List persons, Predicate predicate) {
persons.stream()
.filter(predicate)
.map(p -> p.getName())
.forEach(name -> System.out.println(name));
}
}
Instead of
Array.sort(myArray);
Use...
Arrays.parallelSort(myArray);
Instead of...
Person getEmployee(@PathParam("dept") Long dept, @QueryParam("id") Long id)
Do...
Person getEmployee(@PathParam Long dept, @QueryParam Long id)
Since params names as same as var names.
List<String> names = Arrays.asList("Smith", "Adams", "Crawford");
List<Person> people = peopleDAO.find("London");
// Using anyMatch and method reference
List<Person> anyMatch = people.stream().filter(p -> (names.stream().anyMatch(p.name::contains))).collect(Collectors.toList());
// Using reduce
List<Person> reduced = people.stream().filter(p -> names.stream().reduce(false (Boolean b, String keyword) -> b || p.name.contains(keyword), (l, r) -> l | r)).collect(Collectors.toList());
Clock clock = Clock.systemUTC(); //return the current time based on your system clock and set to UTC.
Clock clock = Clock.systemDefaultZone(); //return time based on system clock zone
long time = clock.millis(); //time in milliseconds from January 1st, 1970