2019-09-10-Collectors类的tomap()方法

2019-12-23  本文已影响0人  一_贫

https://www.jianshu.com/p/267c53dd4295

解决Key冲突
上面的例子工作得很好,但是如果有一个重复的键会发生什么呢?

让我们想象一下,我们在每本书的发行年份为地图设置了键

public Map<Integer, Book> listToMapWithDupKeyError(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity()));
}
鉴于我们之前的书籍清单,我们将看到一个非法状态例外:

@Test(expected = IllegalStateException.class)
public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() {
convertToMap.listToMapWithDupKeyError(bookList);
}
要解决这个问题,我们需要使用另一种方法和附加参数mergefunction:

Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
让我们引入一个合并函数,它指出在发生冲突的情况下,我们保留现有条目:

public Map<Integer, Book> listToMapWithDupKey(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(),
(existing, replacement) -> existing));
}
或者,换句话说,我们获得了第一个胜利行为:

@Test
public void whenMapHasDuplicateKeyThenMergeFunctionHandlesCollision() {
Map<Integer, Book> booksByYear = convertToMap.listToMapWithDupKey(bookList);
assertEquals(2, booksByYear.size());
assertEquals("0395489318", booksByYear.get(1954).getIsbn());
}

上一篇下一篇

猜你喜欢

热点阅读