1

The idea:

I have an object

public class Book(){
  private String name;
  private Integer nbOfPage;
  public Book()
  ...
}

And I got a list of this Object

List<Book> books = new ArrayList<Book>();

Now I was wondering if in guava or another librairie, there was a quick way to get a list of all the different names from all the books I got, something I could do:

List<String> names = new ArrayList<String>();
for (Book aBook : books){
   if (!names.contains(aBook.getName()){
        names.add(aBook.getName());
   }
}

I think this way is a bit "heavy", my book list can have from 200 to 1200 books.

Regards,

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112

2 Answers2

2

Use Guava's Multimaps.index. It does exactly what you'd expect it does.

List<Book> books = ...

Function<Book,String> bookToName = new Function<Book,String>() {
  String apply(Book b) { return b.getName(); }
}

Multimap<String,Book> booksByName = Multimaps.index(books, bookToName);

Then, play around with your Multimap, like booksByName.keys() if you need only the names.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
1

Use a Set (such as HashSet) for the book names collection, this way you don't have to check every time whether you already have the current book name. You can insert elements in constant time into a HashSet, and you will have no duplicates. Make sure you have a good hashCode() method and a corresponding equals, see this: What issues should be considered when overriding equals and hashCode in Java?

A faster solution does not exist, because you have to iterate over all the books at least once.

Community
  • 1
  • 1
lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • Well, IMHO this is not a "first good improvement", but all you can do. You cannot get faster than that... – lbalazscs Feb 14 '13 at 09:54