Reputation: 47
I have a linked list of objects (Books, which fields are title, author and others). Why this implementation of sorting by title gives wrong results?
import java.util.*;
public class sort
{
public static void main(String[] args)
{
LinkedList<Book> l = new LinkedList<>();
l.add(new Book("Vargas Fred", "Il morso della reclusa"));
l.add(new Book("Postorino Rossella", "Le assaggiatrici"));
l.add(new Book("Bythell Shaun", "Una vita da libraio"));
l.add(new Book("Simenon Georges", "Il fondo della bottiglia"));
Collections.sort(l, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.title.length() - o2.title.length();
}
});
for(Book i : l)
{
System.out.println(i.title);
}
}
}
Expected: - Il fondo della bottiglia - Il morso della reclusa - Le assaggiatrici - Una vita da libraio
Result: - Le assaggiatrici - Una vita da libraio - Il morso della reclusa - Il fondo della bottiglia
Upvotes: 0
Views: 77
Reputation: 3470
This should solve your problem. I'm using lambdas and JDK 8
Here's an example Book
class:
public class Book {
final String author;
final String title;
public Book(String author, String title) {
this.author = author;
this.title = title;
}
public String title() {
return this.title;
}
public String author() {
return this.author;
}
}
Now the comparison happens here:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortTest {
public static void main(String... args) {
List<Book> l = new ArrayList<>();
l.add(new Book("Vargas Fred", "Il morso della reclusa"));
l.add(new Book("Postorino Rossella", "Le assaggiatrici"));
l.add(new Book("Bythell Shaun", "Una vita da libraio"));
l.add(new Book("Simenon Georges", "Il fondo della bottiglia"));
Collections.sort(l, Comparator.comparing(Book::title));
l.forEach(book -> System.out.println(book.title));
}
}
Upvotes: 0
Reputation: 2218
If you want to sort the books by Alphabetical order rather than the length of the title, you need to use this:
return o1.title.compareTo(o2.title);
Upvotes: 2