【发布时间】:2019-04-10 01:10:17
【问题描述】:
如何从 List<Book> 中获取一组类别 Strings 且只有唯一值?
我尝试使用流,但我错过了一些东西。
class Book {
int id;
String[] categories;
// getters and setters
}
List<Book> books = Arrays.asList(
new Book(1,{"Java" , "Computers"}),
new Book(1,{"Python" , "C++" }),
new Book(1,{"Java" , "IT"})
);
books.stream().map(VolumeInfo::getCategories).toArray(String[]::new);
【问题讨论】:
-
另一个变体可能是:
String[] arr = books.stream().map(Book::getCategories).flatMap(Arrays::stream).collect(Collectors.toSet()).stream().toArray(String[]::new);不需要 distinct,因为 Set 不能有重复项。