[集合操作]List对象数组获取元素值非空对象及根据对象元素值排序取最大&取对象数组的对象元素集合&条件去重&条件分组

摘要:
如果有一个如下图所示的列表,我需要首先过滤具有空url的列表,然后根据id对其进行分组,以获得具有最大日期字段的对象,形成一个新的集合Listdata=[{“date”:“2018-10-12”,id:“1”,url:“hdjf”},{“date”:“2018年10月13日”,id:“1”、url:,]代码如下:Groovy:Listes=data.findAll{it.url!

如果有个List如下图所示,我需要把这个List先把 url 为空的过滤,然后根据id分组,取date字段最大的对象,形成新的集合

List data = [
  {"date":"2018-10-12", id:"1",url:"hdjf"},
  {"date":"2018-10-13", id:"1",url:"hdjf"}, 
  {"date":"2018-10-12", id:"2",url:"hdjf"},
  {"date":"2018-10-13", id:"2"},  
  {"date":"2018-10-12", id:"3",url:"hdjf"},
  {"date":"2018-10-13", id:"3"},       
]

代码如下:

Groovy:

List eles = data.findAll {it.url != null}.groupBy {it.id}.collect {it -> it.value.max{it.date}}
findAll过滤之后是个新的List,然后根据 id GroupBy 得到的是个如下的Map
Map = [
1:[{"date":"2018-10-12", id:"1",url:"hdjf"},{"date":"2018-10-13", id:"1",url:"hdjf"}],
2:[{"date":"2018-10-12", id:"1",url:"hdjf"}],
3:[{"date":"2018-10-12", id:"1",url:"hdjf"}]
]

最后调用 collect 遍历Map ,每一项Item 获取group之后的最大的

Java代码参考:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class Main {
  public static void main(String...args){
    Map<Type, Food> o =  
    Food.menu.stream().collect(
        Collectors.groupingBy(Food::getType,
            Collectors.collectingAndThen(
                Collectors.reducing((Food d1, Food d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2),
                    Optional::get)));
    
    System.out.println(o);
    
  }
}
enum Type { MEAT, FISH, OTHER }
class Food {

  private final String name;
  private final boolean vegetarian;
  private final int calories;
  private final Type type;

  public Food(String name, boolean vegetarian, int calories, Type type) {
      this.name = name;
      this.vegetarian = vegetarian;
      this.calories = calories;
      this.type = type;
  }

  public String getName() {
      return name;
  }

  public boolean isVegetarian() {
      return vegetarian;
  }

  public int getCalories() {
      return calories;
  }

  public Type getType() {
      return type;
  }
  @Override
  public String toString() {
      return name;
  }

  public static final List<Food> menu =
          Arrays.asList( new Food("pork", false, 1800, Type.MEAT),
                         new Food("beef", false, 7100, Type.MEAT),
                         new Food("chicken", false, 1400, Type.MEAT),
                         new Food("french fries", true, 1530, Type.OTHER),
                         new Food("rice", true, 3510, Type.OTHER),
                         new Food("season fruit", true, 1120, Type.OTHER),
                         new Food("pizza", true, 5150, Type.OTHER),
                         new Food("prawns", false, 1400, Type.FISH),
                         new Food("salmon", false, 4150, Type.FISH));
}

 第二:取对象数组中对象元素的集合

public static void main(String[] args) {
        List<Student> stuList = new ArrayList<Student>();
        Student st1 = new Student("123","aaa");
        Student st2 = new Student("234","bbb");
        Student st3 = new Student("345","ccc");
        Student st4 = new Student("345","ccc");
        stuList.add(st1);
        stuList.add(st2);
        stuList.add(st3);
        stuList.add(st4);
        //1.提取出list对象中的一个属性
        List<String> stIdList1 = stuList.stream()
                .map(Student::getId)
                .collect(Collectors.toList());
        stIdList1.forEach(s -> System.out.print(s+" "));
        System.out.println();
        System.out.println("----------");
        
        //2.提取出list对象中的一个属性并去重
        List<String> stIdList2 = stuList.stream()
                .map(Student::getId).distinct()
                .collect(Collectors.toList());
        stIdList2.forEach(s -> System.out.print(s+" "));
        /*    结果:
            123 234 345 345  
            ----------
            123 234 345 
        */
    }

第三 条件去重

普通去重  distinct()函数能够根据简单类型直接去重

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 5, 5, 5, 6, 7);
 
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers);//1, 2, 3, 4, 5, 6, 7

如果需要对类型List<User>去重

首先定义一个过滤器:
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}
List<User> users = new LinkedList<>();
users.add(new User("Jim"));
users.add(new User("Jim"));
users.add(new User("Tom"));
users.add(new User("Leo"));
//愉快的去重
List<User> distinctUsers = users.stream()
        .filter(distinctByKey(User::getName))
        .collect(Collectors.toList());

System.out.println(distinctUsers);//[Jim, Tom, Leo]

四。条件分组

List<User> users = new LinkedList<>();
users.add(new User("Jim", 12));
users.add(new User("John", 18));
users.add(new User("Tom", 21));
users.add(new User("Leo", 30));
users.add(new User("Kate", 44));
users.add(new User("Lio", 50));
 
Map<String, List<User>> tripleUsers = users.stream()
        .collect(Collectors.groupingBy((Function<User, String>) user -> {
    String key;
    if (user.getAge() <= 20) {
        key = "less20";
    } else if (user.getAge() <= 40) {
        key = "less40";
    } else {
        key = "more40";
    }
    return key;
}, Collectors.toList()));
 
System.out.println(tripleUsers);
//{more40=[Kate, Lio], less40=[Tom, Leo], less20=[Jim, John]}

//根据年龄分组

Map<String, List<User>> studlistGrouped = studlist.stream().collect(Collectors.groupingBy(w -> w.age));
 

免责声明:文章转载自《[集合操作]List对象数组获取元素值非空对象及根据对象元素值排序取最大&amp;amp;取对象数组的对象元素集合&amp;amp;条件去重&amp;amp;条件分组》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Salesforce Apex学习 : 利用Schema命名空间中的DescribeSObjectResult类型来获取sObject对象的基本信息eclipse里面有2个空格设置下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java使用jdbc对sqlite 添加、删除、修改的操作

package com.jb.jubmis.Dao.DaoImpl; import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import...

JS将时间戳转化为时间

//将时间戳转化为时间 function timestampToTime(timestamp) { var date = new Date(timestamp * 1000);//时间戳为10位需*1000,13位的话不需要 Y = date.getFullYear() + "-"; M = (date.getMonth()+...

Python任务调度模块 – APScheduler

APScheduler是一个Python定时任务框架,使用起来十分方便。提供了基于日期、固定时间间隔以及crontab类型的任务,并且可以持久化任务、并以daemon方式运行应用。目前最新版本为3.0.x。在APScheduler中有四个组件:触发器(trigger)包含调度逻辑,每一个作业有它自己的触发器,用于决定接下来哪一个作业会运行。除了他们自己初始...

MySQL sql语句获取当前日期|时间|时间戳

1.1 获得当前日期+时间(date + time)函数:now() MySQL> select now(); +———————+ | now() | +———————+ | 2013-04-08 20:56:19 | +———————+ 除了 now() 函数能获得当前的日期时间外,MySQL 中还有下面的函数: current_time...

签名:实现参数字典排序,然后拼接为url参数形式

在很多地方请求参数需要做处理例如: 步骤 1.参数字典排序。 2.拼接字符。 /// <summary> ///生成签名 /// </summary> /// <param name="paramlst">参数列表</param>...

ORM之单表操作

ORM简介 MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松更换数据库,这极大的减轻了开发人员的工作量,不需要面对因数据库变更而导致的无效劳动 ORM是“对象-关系-映射”的简称。 一、单表操作 创建表 1、创建模型 创建名为book的app,在...