groupingBy returns Key 的对象作为 Map 应该使用 String

groupingBy returns Object for key as Map when it should use String

假设我有一个品牌对象列表。 POJO 包含一个 returns 字符串的 getName()。我想建立一个 Map<String, Brand> 除此之外,字符串是名称...但我希望密钥 不区分大小写

如何使用 Java 流来完成这项工作?正在尝试:

brands.stream().collect(Collectors.groupingBy(brand -> brand.getName().toLowerCase()));

不起作用,我认为这是因为我没有正确使用 groupBy。

Collect the results into a case insensitive map

Map<String, Brand> map = brands
     .stream()
     .collect(
          Collectors.toMap(
              Brand::getName, // the key
              Function.identity(), // the value
              (first, second) -> first, // how to handle duplicates
              () -> new TreeMap<String, Brand>(String.CASE_INSENSITIVE_ORDER))); // supply the map implementation

Collectors#groupBy 在这里不起作用,因为它 returns 一个 Map<KeyType, List<ValueType>>,但你不想要一个 List 作为值,你只想要一个 Brand,据我了解。