How to get distinct element from a list?

Pramish Luitel :

Below is the book list I do have and is stored via LinkedList. I can get the title, year, price and genres by their methods using getTitle(), getYear(), getPrice() and getGenres().

I do not have any problem regarding retrieving titles, years and price but the genres should which I am getting must be distinct i.e. in the book list I have Programming, Programming, Programming, Drama, Thriller.

When I use below function then I do get all of the genres which I should get Programming only once.

LinkedList<Book> books = new LinkedList<Book>();

books.add(new Book("Java",2000,"Programming", "$20"));
books.add(new Book("Swift",2001,"Programming", "$30"));
books.add(new Book("C#",1990,"Programming", "$40"));
books.add(new Book("The Alchemist",2010,"Drama", "$10"));
books.add(new Book("Goosebumps",2010,"Thriller", "$5"));

private void getGenres(){
     for (Genre genre : booksList){
            System.out.println(genre.toString());
}
}

I am getting output as:

Programming
Programming
Programming
Drama
Thriller

But the output I should get is:

Programming
Drama
Thriller

Help from you guys.

I hope you understand guys.

Thanks in advance.

Michal Horvath :

For java 8 and newer you can use streams to filter genres from books and then get distinct values:

LinkedList<Book> books = ...;

private void getGenres(){
     List<Genre> genres = books.stream()
             .map(x -> x.getGenre())
             .distinct()
             .collect(Collectors.toList());
     for (Genre genre : genres){
            System.out.println(genre);
     }
}

Your type Genre needs to implement Comparable<T> interface:

public class Genre implements Comparable<Genre>{

    String name;

    public Genre(String name) {
        super();
        this.name = name;
    }

    @Override
    public int compareTo(Genre otherGenre) {
        return name.compareTo(otherGenre.name);
    }

    @Override
    public String toString() {
        return name;
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=149766&siteId=1