How to retrieve distinct variables from a list using Java functional programming concepts
It's been over two months since I created my Hashnode blog and I’m yet to publish an article. If you ask me why I have not written anything yet, my default response would probably be something like “I had project deadlines, deployments, code reviews” and the list of excuses goes on. Therefore I decided to stop making excuses, take action and sign up for the Hashnode Bootcamp II. First day of Bootcamp, Chris Bongers, author of daily-dev-tips blog, challenged us to “create an article that would help your past self solve a problem you’ve encountered”. I'm excited to take up the challenge and here goes my first article.
Enough about me, let's get going. In this article I will solve the problem of retrieving distinct variables from a list. Suppose you have a list of books, containing book objects with title, author, and price, and you wanted to efficiently retrieve all the unique authors from the book list. See below code example of the book class to create the book objects.
public class Book {
private String title;
private String author;
private double price;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Before Java 8, to achieve this you would have to:
- Declare a Set variable.
- Create a for loop to iterate through each book object.
- Retrieve the author from the book object.
- Add the author to the Set variable.
As shown in the code example below.
public class ForLoopDemo {
public static void main(String[] args) {
List<Book> books = getBooks();
Set<String> authors = new HashSet<>();
for (Book book : books) {
authors.add(book.getAuthor());
}
System.out.println(authors);
}
private static List<Book> getBooks() {
List<Book> books = Arrays.asList(new Book("Born a crime", "Trevor Noah", 10),
new Book("Long Walk To Freedom", "Nelson Mandela", 20),
new Book("The 5 AM Club", "Robin Sharma", 15),
new Book("Becoming Michelle Obama", "Michelle Obama", 20),
new Book("The Monk Who Sold His Ferrari", "Robin Sharma", 12));
return books;
}
}
Java 8 introduced great functional programming concepts such as Stream API and lambda expression. Stream API provides a functional approach to processing a sequence of elements. Lambda expression is a block of code that represents a function without a declaration and thus does not necessarily have a name, access modifier and a return type.
For retrieval of distinct authors from the book list, you can use stream map() function from the Stream class. The stream map() function converts one type of object into another different type of object by using a mapper function. The stream map() function achieves this conversion by taking a stateless function as an argument and applying it to the stream object.
In the below code example I created a Book list called books. The list contains book objects with title, author and price. I then retrieve the authors from the book list by:
Using stream.map() function and passing it a lambda expression (book -> book.getAuthor) to retrieve the author.
Accumulating the results to a Set variable.
public class StreamsMapDemo {
public static void main(String[] args) {
List<Book> books = getBooks();
Set<String> authors = books.stream().map(book -> book.getAuthor()).collect(Collectors.toSet());
System.out.println(authors);
}
private static List<Book> getBooks() {
List<Book> books = Arrays.asList(new Book("Born a crime", "Trevor Noah", 10),
new Book("Long Walk To Freedom", "Nelson Mandela", 20),
new Book("The 5 AM Club", "Robin Sharma", 15),
new Book("Becoming Michelle Obama", "Michelle Obama", 20),
new Book("The Monk Who Sold His Ferrari", "Robin Sharma", 12));
return books;
}
}
The book list, books, in the code block above, Robin Sharma appears twice as he has two books to his name. However from the result image below, Robin Sharma appears only once. This demonstrates a successful retrieval of unique authors from the list.
Results
Thank you for reading and I look forward to your comments and feedback.