栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

基于条件和顺序的Java 8 Lambda过滤

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于条件和顺序的Java 8 Lambda过滤

使用

toMap
收集器:

Collection<Student> values = students.stream()     .collect(toMap(Student::getName,  Function.identity(),  BinaryOperator.maxBy(Comparator.comparingInt(Student::getAge))))     .values();

说明

我们正在使用以下重载

toMap

toMap​(Function<? super T,? extends K> keyMapper,      Function<? super T,? extends U> valueMapper,      BinaryOperator<U> mergeFunction)
  • Student::getName
    上面的
    keyMapper
    函数用于提取映射键的值。
  • Function.identity()
    上面的
    valueMapper
    函数用于提取地图值的值,其中
    Function.identity()
    简单地返回源中它们本身即
    Student
    对象的元素。
  • BinaryOperator.maxBy(Comparator.comparingInt(Student::getAge))
    上面的合并函数用于“确定在键冲突时要返回哪个Student对象,即当两个给定的学生具有相同的名称时”,在这种情况下采用最早的
    Student
  • 最后,调用
    values()
    返回给我们一批学生。

等效的C#代码为:

var values = students.GroupBy(s => s.Name, v => v,    (a, b) => b.OrderByDescending(e => e.Age).Take(1)).SelectMany(x => x);

说明 (针对那些不熟悉.NET的人)

我们正在使用以下扩展方法

GroupBy

System.Collections.Generic.IEnumerable<TResult> GroupBy<TSource,TKey,TElement,TResult>        (this System.Collections.Generic.IEnumerable<TSource> source,          Func<TSource,TKey> keySelector,          Func<TSource,TElement> elementSelector,      Func<TKey,System.Collections.Generic.IEnumerable<TElement>,TResult> resultSelector);
  • s => s.Name
    上面的
    keySelector
    函数用于提取要分组的值。
  • v => v
    上面的
    elementSelector
    函数用于提取值,即
    Student
    它们所拥有的对象。
  • b.OrderByDescending(e => e.Age).Take(1)
    以上是
    resultSelector
    给出的
    IEnumerable<Student>
    代表年龄
    b
    最大的学生的。
  • 最后,我们申请
    .SelectMany(x => x);
    将结果折叠
    IEnumerable<IEnumerable<Student>>
    IEnumerable<Student>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570438.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号