- 错误使用案例:忽略了类型参数
Listlist = Arrays.asList("Apple", "Banana", "Orange"); Set set = list.stream() .collect(Collectors.toSet());
这里将一个List
正确的做法是指定类型参数:
Listlist = Arrays.asList("Apple", "Banana", "Orange"); Set set = list.stream() .collect(Collectors.toSet());
- 错误使用案例:使用错误的收集器
Listlist = Arrays.asList("Apple", "Banana", "Orange"); Map map = list.stream() .collect(Collectors.toList());
这里将一个List
Listlist = Arrays.asList("Apple", "Banana", "Orange"); Map map = list.stream() .collect(Collectors.toMap(Function.identity(), String::length));
- 错误使用案例:未处理重复键的情况
Listlist = Arrays.asList("Apple", "Banana", "Orange", "Apple"); Map map = list.stream() .collect(Collectors.toMap(Function.identity(), String::length));
这里将一个List
正确的做法是处理重复键的情况,可以通过提供一个合并函数来解决:
Listlist = Arrays.asList("Apple", "Banana", "Orange", "Apple"); Map map = list.stream() .collect(Collectors.toMap(Function.identity(), String::length, (existing, replacement) -> existing));