1. list转map
1.1. 需求
- 将两个list转为一个list
- 然后对这个list,根据list中的对象的某一个属性,例如
id
进行去重
1.2. 将两个list转为一个list
newLists.addAll(oldLists);
1.3. 将list转map
Map<String,FqtSysPermission> immutableMap = Maps.uniqueIndex(newLists,item-> item.getId() );
1.3.1. 核心方法(Maps.uniqueIndex())
英文描述的非常详细
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* <pre>{@code
* Color red = new Color("red", 255, 0, 0);
* ...
* ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
*
* Map<String, Color> colorForName =
* uniqueIndex(allColors, toStringFunction());
* assertThat(colorForName).containsEntry("red", red);
* }</pre>
*
* <p>If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
*/
@CanIgnoreReturnValue
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
// TODO(lowasser): consider presizing the builder if values is a Collection
return uniqueIndex(values.iterator(), keyFunction);
}
1.4. 完整代码
private List<FqtSysPermission> mergeList(List<FqtSysPermission> newLists, List<FqtSysPermission> oldLists) {
// 将两个list合并
newLists.addAll(oldLists);
// 得到两个list的并集
Map<String,FqtSysPermission> immutableMap = Maps.uniqueIndex(newLists,item-> item.getId() );
return Lists.newArrayList(immutableMap.values());
}