📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
1. Overview
Initial setup
- Make sure you're compiling with a Java 8 JDK.
- Pick a section of the codebase to apply them to.
- In the beginning, pick a small number of changes to implement.
2. Migrating Source Code to Java 8 Tips
How to use Lambda expressions?
- Runnable
- Callable
- Comparator
- FileFilter
- PathMatcher
- EventHandler, etc
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
getDs().save(new CappedPic(title));
}
}, 0, 500, MILLISECONDS);
executorService.scheduleAtFixedRate(() -> getDs()
.save(new CappedPic(title)), 0, 500, MILLISECONDS);
Understand the impact of applying lambda expressions
- Larger anonymous inner classes may not be very readable in a lambda form.
- There may be additional changes and improvements you can make.
Runnable runnable = new Runnable() {
@Override
public void run() {
datastoreProvider.register(database);
Assert.assertNull(database.find(User.class, "id", 1).get());
Assert.assertNull(database.find(User.class, "id", 3).get());
User foundUser = database.find(User.class, "id", 2).get();
Assert.assertNotNull(foundUser);
Assert.assertNotNull(database.find(User.class, "id", 4).get());
Assert.assertEquals("Should find 1 friend", 1, foundUser.friends.size());
Assert.assertEquals("Should find the right friend", 4, foundUser.friends.get(0).id);
}
};
Runnable runnable = () -> {
datastoreProvider.register(database);
Assert.assertNull(database.find(User.class, "id", 1).get());
Assert.assertNull(database.find(User.class, "id", 3).get());
User foundUser = database.find(User.class, "id", 2).get();
Assert.assertNotNull(foundUser);
Assert.assertNotNull(database.find(User.class, "id", 4).get());
Assert.assertEquals("Should find 1 friend", 1, foundUser.friends.size());
Assert.assertEquals("Should find the right friend", 4, foundUser.friends.get(0).id);
};
Runnable runnable = () -> {
assertUserMatchesSpecification(database, datastoreProvider);
};
Runnable runnable = () -> assertUserMatchesSpecification(database, datastoreProvider);
How to use new Collection Methods?
- Find the for loop statements in your project, for example :
for (Person person : listOfPerson) {
System.out.println(" Person name : " + person.getName());
}
listOfPerson.forEach((person) -> System.out.println(" Person name : " + person.getName()));
- If you find for loop like this :
for (Class<? extends Annotation > annotation : INTERESTING_ANNOTATIONS) {
addAnnotation(annotation);
}
INTERESTING_ANNOTATIONS.forEach((annotation) -> addAnnotation(annotation));
Stream API - forEach
public void addAllBooksToLibrary(Set<Book> books) {
for (Book book: books) {
if (book.isInPrint()) {
library.add(book);
}
}
}
public void addAllBooksToLibrary(Set <Book> books) {
books.stream()
.filter(book -> book.isInPrint())
.forEach(library::add);
}
books.stream()
.filter(Book::isInPrint)
.forEach(library::add);
Streams API - collect
List <ProjectEntity> listOfProjects = getProjects();
List <ProjectDTO> ProjectDTOs= new ArrayList<ProjectDTO>();
for (ProjectEntity projectEntity : listOfProjects ) {
ProjectDTOs.add(projectEntity .getId());
}
List<ProjectDTO> projectDTOs= listOfProjects.stream().map(PrjectDTO::getId).collect(Collectors.toList());
How to use Optional Class?
- If you see "Assignment to null" for fields, you may want to consider turning this field into an Optional. For example, in the code below, the line where an offset is assigned will be flagged:
private Integer offset;
public Builder offset(int value) {
offset = value > 0 ? value : null;
return this;
}
// more code...
That's because in another method, the code checks to see if this value has been set before doing something with it:
if (offset != null) {
cursor.skip(offset);
}
private Optional<Integer> offset;
public Builder offset(int value) {
offset = value > 0 ? Optional.of(value) : Optional.empty();
return this;
}
// more code...
Then you can use the methods on Optional instead of performing null-checks. The simplest solution is:
if (offset.isPresent()) {
cursor.skip(offset);
}
offset.ifPresent(() -> cursor.skip(offset));
- If you have code looks like
public Customer findFirst() {
if (customers.isEmpty()) {
return null;
} else {
return customers.get(0);
}
}
public Optional<Customer> findFirst() {
if (customers.isEmpty()) {
return Optional.empty();
} else {
return Optional.ofNullable(customers.get(0));
}
}
- If you found the code in your project looks like :
Customer firstCustomer = customerDao.findFirst();
if (firstCustomer == null) {
throw new CustomerNotFoundException();
} else {
firstCustomer.setNewOffer(offer);
}
Optional<Customer> firstCustomer = customerDao.findFirst();
firstCustomer.orElseThrow(() -> new CustomerNotFoundException())
.setNewOffer(offer);
Simple use Cases
final List<CommissionDto> commissionDtos = Lists.newLinkedList();
for (CassandraOfferCommission cassandraOfferCommission : cassandraOfferCommissions) {
commissionDtos.add(buildCommissionDto(cassandraOfferCommission));
}
return commissionDtos;
return cassandraOfferCommissions.stream().map(this::buildCommissionDto).collect(toList());
return getRanges().stream()
.filter(range -> range.containsPrice(amount))
.findFirst()
.orElseThrow(() -> new RangeNotFoundException(String.format("No matching range found for amount %s", amount)));
quoteDetails.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().getFee()))
3. Related Java 8 Top Posts
- Java 8 Lambda Expressions
- Java 8 Functional Interfaces
- Java 8 Method References
- Java 8 Stream API
- Java 8 Optional Class
- Java 8 Collectors Class
- Java 8 StringJoiner Class
- Java 8 Static and Default Methods in Interface
- Guide to Java 8 forEach Method
- Handle NullPointerException in Controller, Service and DAO Layer using Java 8 Optional Class
- How to Use Java 8 Stream API in Java Projects
- Migrating Source Code to Java 8
Comments
Post a Comment
Leave Comment