【问题标题】:How get arrays of strings properties from list of objects [duplicate]如何从对象列表中获取字符串属性数组[重复]
【发布时间】: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 不能有重复项。

标签: java arrays list


【解决方案1】:

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

String[] arr = books.stream()
                    .map(Book::getCategories)
                    .flatMap(Arrays::stream)
                    .distinct()
                    .toArray(String[]::new);

这将产生Array:

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

【讨论】:

  • 好的,但是我得到了一个数组列表,但我想在一个数组中获取所有值
  • 非常感谢!这正是我所需要的。
猜你喜欢
  • 2017-08-09
  • 2021-11-28
  • 2018-08-30
  • 2015-11-11
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2021-05-24
相关资源
最近更新 更多