Java 如何从对象列表中获取字符串数组属性

Java 如何从对象列表中获取字符串数组属性,java,arrays,list,Java,Arrays,List,如何从只有唯一值的列表中获取类别字符串数组 我试着用stream,但我错过了一些东西 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

如何从只有唯一值的
列表
中获取类别
字符串
数组

我试着用stream,但我错过了一些东西

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);

教材{
int-id;
字符串[]类别;
//接球手和接球手
}
List books=Arrays.asList(
新书(1,{“Java”,“Computers”}),
新书(1,{“Python”,“C++”}),
新书(1,{“Java”,“IT”})
);
books.stream().map(VolumeInfo::getCategories).toArray(String[]::new);

您可以调用以仅获取唯一值。但是,由于
getCategories
返回一个
String[]
因此,您需要
flatMap
来获得一个
String[]

String[] arr = books.stream()
                    .map(Book::getCategories)
                    .flatMap(Arrays::stream)
                    .distinct()
                    .toArray(String[]::new);
这将生成
数组

[Java, Computers, Python, C++, IT]

好的,但是我得到了一个数组列表,但是我想得到一个数组中的所有值,很多!这就是我所需要的。另一个变体可以是:
String[]arr=books.stream().map(Book::getCategories)、flatMap(Arrays::stream)、collector(Collectors.toSet()).stream().toArray(String[]::new)不需要distinct,因为集合不能有重复项。