番石榴的排序方式根据另一个列表? [英] Guava way of sorting List according to another list?
问题描述
我有列表<整数>
包含我的用户ID。在数据库查询之后,我正在检索 List< User>
。我想根据第一个Id列表订购此列表。 列表<用户>
可能不包含部分ID。什么是Guava排序这个列表的方法?
I have List<Integer>
consisting Ids of my Users. And after a database query, I am retrieving List<User>
. I would like to order this list according to first Id list. List<User>
may not include some of the Ids. What is the Guava way for sorting this list?
推荐答案
使用Guava的完全功能方式将结合 Ordering#explicit()
with 订购#onResultOf()
The fully "functional" way, using Guava, would combine Ordering#explicit()
with Ordering#onResultOf()
public class UserService {
@Inject private UserDao userDao;
public List<User> getUsersWithIds(List<Integer> userIds) {
List<User> users = userDao.loadUsersWithIds(userIds);
Ordering<User> orderById = Ordering.explicit(userIds).onResultOf(UserFunctions.getId());
return orderById.immutableSortedCopy(users);
}
}
你可以声明一个内联的匿名函数,但我喜欢在单独的类中将我的函数声明为静态工厂方法,以获得更清晰的代码(Java函数声明的详细程度隐藏在实用程序类中):
You could declare an anonymous function inline, but I like to declare my functions as static factory methods in a separate class, for a cleaner code (the verbosity of Java's function declarations is hidden in the utility class):
/**
* Static factory methods to create {@link Function}s for {@link User}s.
*/
public final class UserFunctions {
private UserFunctions() { /* prevents instantiation */ }
/**
* @return a {@link Function} that returns an {@link User}'s id.
*/
public static Function<User, Integer> getId() {
return GetIdFunction.INSTANCE;
}
// enum singleton pattern
private enum GetIdFunction implements Function<User, Integer> {
INSTANCE;
public Integer apply(User user) {
return user.getId();
}
}
}
正如@Arne在评论中所提到的,这可以在Java 8中简化,使用方法引用而不是 UserFunctions
类:
public class UserService {
@Inject private UserDao userDao;
public List<User> getUsersWithIds(List<Integer> userIds) {
List<User> users = userDao.loadUsersWithIds(userIds);
Ordering<User> orderById = Ordering.explicit(userIds).onResultOf(User::getId);
return orderById.immutableSortedCopy(immutableSortedCopy(users));
}
}
这篇关于番石榴的排序方式根据另一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!