Java Stream:获取最新版本的用户记录 [英] Java Stream: get latest version of user records

查看:214
本文介绍了Java Stream:获取最新版本的用户记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User对象列表,定义如下:

I have a list of User objects, defined as follows:

public class User {
    private String userId; // Unique identifier
    private String name;
    private String surname;
    private String otherPersonalInfo;
    private int versionNumber;
    }
    public User(String userId, String name, String surname, String otherPersonalInfo, int version) {
      super();
      this.name = name;
      this.surname = surname;
      this.otherPersonalInfo = otherPersonalInfo;
      this.version = version;
    }
}

示例清单:

List<User> users = Arrays.asList(
  new User("JOHNSMITH", "John", "Smith", "Some info",     1),
  new User("JOHNSMITH", "John", "Smith", "Updated info",  2),
  new User("JOHNSMITH", "John", "Smith", "Latest info",   3),
  new User("BOBDOE",    "Bob",  "Doe",   "Personal info", 1),
  new User("BOBDOE",    "Bob",  "Doe",   "Latest info",   2)
);

我需要一种方法来过滤此列表,以便我只获得每个用户的最新版本,即:

I need a way to filter this list such that I get only the latest version for each user, i.e:

{"JOHNSMITH", "John", "Smith", "Latest info", 3},
{"BOBDOE", "Bob", "Doe", "Latest info", 2}

什么是使用Java8 Stream API实现这一目标的最佳方法是什么?

What's the best way to achieve this by using Java8 Stream API?

推荐答案

HashMap<String, User> map = users.stream().collect(Collectors.toMap(User::getUserId, 
            e -> e, 
            (left, right) -> {return left.getVersion() > right.getVersion() ? left : right;}, 
            HashMap::new));
System.out.println(map.values());

以上代码打印:

[User [userId=BOBDOE, name=Bob, surname=Doe, otherPersonalInfo=Latest info, version=2], User [userId=JOHNSMITH, name=John, surname=Smith, otherPersonalInfo=Latest info, version=3]]

说明:
toMap方法有4个参数:

Explanation: toMap method takes 4 arguments:


  1. keyMapper 生成密钥的映射函数

  2. valueMapper 用于生成值的映射函数

  3. mergeFunction 一个合并函数,用于解决与提供给Map.merge的相同键关联的值之间的冲突( Object,Object,BiFunction)

  4. mapSupplier 一个函数,它返回一个新的空Map,结果将插入其中

  1. keyMapper a mapping function to produce keys
  2. valueMapper a mapping function to produce values
  3. mergeFunction a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
  4. mapSupplier a function which returns a new, empty Map into which the results will be inserted








  1. 第一个arg是User :: getUserId()获取密钥。

  2. 第二个arg是一个返回User对象的函数它是。

  3. 第三个arg是一个通过比较和保持用户最新版本来解决冲突的函数。

  4. 第四个arg是新的 HashMap的方法。

  1. First arg is User::getUserId() to get key.
  2. Second arg is a function that returns the User object as it is.
  3. Third arg is a function which solves collision by comparing and keeping the User with latest version.
  4. Fourth arg is the "new" method of HashMap.

这篇关于Java Stream:获取最新版本的用户记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆