Charles Sexton Charles Sexton - 1 year ago 70
Java Question

Function interface as a lambda to sort a collection?

I am studying lambda expressions and I am struggling with on how to use the java.util.function.Function to sort a collection. Could someone help me or at give me some pointers on how to achieve this?

I have a book POJO and a class that stores books in a collection. I am trying to use a lambda expression of the Function interface to return the same collection but sorted. I could use Collections.sort() and return it that way but I was thinking there was a way to do it with the Function interface.

public class BookTable {

private Map<Integer, Book> bookMap;

public BookTable() {
this.bookMap = new HashMap<>();

public void addBook(Book book) {
bookMap.put(size(), book);

public int size() {
return bookMap.size();

public List<Book> getRecord(int key) {
return Collections.singletonList(bookMap.get(key));

public List<Book> getRecordsWhere(Predicate<Book> predicate) {
return bookMap.values()

public List<Book> getSortedRecords(Function<Book, Comparable> fieldExtractor) {
// Return sorted list....


public class Book {

private String title;
private String author;

public String getTitle() {
return title;

public void setTitle(String title) {
this.title = title;

public String getAuthor() {
return author;

public void setAuthor(String author) { = author;

Just a quick test...

public class BookTableTest {

public static void main(String[] args) {

File file = new File("booklist.csv");
BookTable table = new BookTable();

Book book1 = new Book();
book1.setAuthor("Author 1");
book1.setTitle("Title 1");

Book book2 = new Book();
book2.setAuthor("Book 2 Author 1");
book2.setTitle("Book 2 Title 1");

Book book3 = new Book();
book3.setAuthor("The best author");
book3.setTitle("The best title");


System.out.println("## Sorted by Title");

System.out.println("## Sorted by Author");



Answer Source

You can create a Comparator<Book> with your fieldExtractor, and then collect it. Also, I think you wanted a Function<Book, Comparable<Book>>. Like,

public List<Book> getSortedRecords(Function<Book, Comparable<Book>> fieldExtractor) {
    return bookMap.values().stream().sorted(new Comparator<Book>() {
        public int compare(Book o1, Book o2) {
            return fieldExtractor.apply(o1).compareTo(o2);