Map<String, String> phoneBook = people.stream()
                                      .collect(toMap(Person::getName,
                                                     Person::getAddress));

我得到java.lang.IllegalStateException:当找到一个重复的元素时,重复键。

是否有可能忽略这种例外添加值到地图?

当有重复的键时,应该忽略重复的键继续执行。


当前回答

我有同样的情况,发现最简单的解决方案(假设你只是想覆盖重复键的映射值)是:

Map<String, String> phoneBook = 
       people.stream()
           .collect(Collectors.toMap(Person::getName, 
                                  Person::getAddress, 
                                        (key1, key2)-> key2));

其他回答

我有同样的情况,发现最简单的解决方案(假设你只是想覆盖重复键的映射值)是:

Map<String, String> phoneBook = 
       people.stream()
           .collect(Collectors.toMap(Person::getName, 
                                  Person::getAddress, 
                                        (key1, key2)-> key2));

正如在JavaDocs中所说:

如果映射的键包含重复项(根据 Object.equals(Object))时,当异常时抛出IllegalStateException 执行收集操作。如果映射的键可能有 重复,使用toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)代替。

所以你应该使用toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)来代替。只需提供一个合并函数,它将确定将哪个副本放入映射中。

例如,如果你不关心是哪个,打电话就可以了

Map<String, String> phoneBook = people.stream().collect(
        Collectors.toMap(Person::getName, Person::getAddress, (a1, a2) -> a1));

我在分组对象时遇到过这样的问题,我总是用一个简单的方法解决它们:使用java.util.Set执行一个自定义过滤器,以删除重复的对象,无论你选择的属性如下所示

Set<String> uniqueNames = new HashSet<>();
Map<String, String> phoneBook = people
                  .stream()
                  .filter(person -> person != null && !uniqueNames.add(person.getName()))
                  .collect(toMap(Person::getName, Person::getAddress));

希望这对有同样问题的人有所帮助!

为了完整起见,这里介绍了如何将重复项“减少”到只有一个。

如果你同意最后一个:

  Map<String, Person> phoneBook = people.stream()
          .collect(groupingBy(x -> x.name, reducing(null, identity(), (first, last) -> last)));

如果你只想要第一个:

  Map<String, Person> phoneBook = people.stream()
          .collect(groupingBy(x -> x.name, reducing(null, identity(), (first, last) -> first != null ? first : last)));

如果你想要last but“address as String”(不使用identity()作为参数)。

  Map<String, String> phoneBook = people.stream()
          .collect(groupingBy(x -> x.name, reducing(null, x -> x.address, (first, last) -> last)));

因此,本质上,groupingBy与还原收集器配对,开始表现得非常类似于toMap收集器,有一些类似于它的mergeFunction…结果是一样的……

按对象分组

Map<Integer, Data> dataMap = dataList.stream().collect(Collectors.toMap(Data::getId, data-> data, (data1, data2)-> {LOG.info("Duplicate Group For :" + data2.getId());return data1;}));