【问题标题】:How to group different lists one inside another?如何将不同的列表分组到另一个列表中?
【发布时间】:2012-09-13 02:01:09
【问题描述】:

我的列表包含三个级别的列表。我使用 JPA 从三个不同的数据库表中获取这些数据。

关于更多细节,我有三个不同的对象(组、类型、项目):一个包含一个包含项目列表的类型列表的组。

我只想从不同的类型和组中获取几个项目,然后像列表一样返回这些项目。

问题是:有没有一种优雅而简单的方法来做到这一点?或者我真的需要获取所有的项目并逐级分组?

【问题讨论】:

  • 您是否尝试过查询这些项目?你尝试了什么?

标签: java jpa collections


【解决方案1】:

番石榴可能会提供一个不错的解决方案:

 Predicate<Group> matchingGroup = ...;
 Predicate<Type> matchingType = ...;

 Function<Group, Type> getType = new Function<Group, Type>(){};
 Function<Type, Item> getItem = new Function...;

 // starting point
 List<Group> myGroups;
 Iterable<Item> filteredItems =
    Iterables.transform(
       Iterables.filter( 
          Iterables.transform(
              Iterables.filter(myGroups, matchingGroup),
              getType),
          matchingType),
       getItem);

或扩展:

 // starting point
 List<Group> myGroups;
 Iterable<Type> types = Iterables.transform(
              Iterables.filter(myGroups, matchingGroup),
              getType);
 Iterable<Item> items = Iterables.transform(
              Iterables.filter(types, matchingType),
              getItem);

可能有一种方法可以使用 Predicates / Functions compose 方法来缩短它。

番石榴是here

【讨论】:

  • 确实是一个不错的解决方案,但不知道是不是很简单。
  • 同意,从 Guava 开始是一种思维转变。但是一旦你开始使用它,你就会开始爱上它。
猜你喜欢
  • 2019-08-20
  • 2017-08-20
  • 2022-01-04
  • 2017-11-18
  • 2014-09-12
  • 2013-03-25
  • 2012-06-24
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多