list转map

1. list转map

1.1. 需求

  1. 将两个list转为一个list
  2. 然后对这个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());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值