Search code examples
javajava-8java-streamcollectors

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


Let's say I have a list of Brand objects. The POJO contains a getName() that returns a string. I want to build a Map<String, Brand> out of this with the String being the name... but I want the key to be case insensitive.

How do I make this work using Java streams? Trying:

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

doesn't work, which I think is because I'm not using groupBy correctly.


Solution

  • 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 won't work here because it returns a Map<KeyType, List<ValueType>>, but you don't want a List as a value, you just want a Brand, from what I've understood.