【问题标题】:ArrayList Grouping By specific conditionsArrayList 按特定条件分组
【发布时间】:2020-07-25 17:26:33
【问题描述】:

我有这些 POJO

class LocaleBook
{
  private String bookId;

  private String bookName;

  private Locale locale;
  //setters & getters
}

class Locale
{
  private String country;

  private String language;
  //setters & getters
}

上面的示例数据是

"alice", "Alice in the wonderland", "GB", "en"
"matrix", "The Matrix", "TH", "en"
"christtree", "The Christmas Tree", "GB", "en"

还有这个方法:

List<LocaleBook> localeBooks = repo.getLocalBooks();

我想按国家和语言将数据分组在一起,我创建了这个 POJO:

class NewPoJo
{
  private String country;

  private String language;

  private List<KeyValuePair> localeBooks = new HashSet<>();
  //setters & getters
}

class KeyValuePair {

    private String label;

    private String value;
    //setters & getters
}

预期输出:

[
   {
      "country":"GB",
      "language":"en",
      "localeBooks":[
         {
            "label":"alice",
            "value":"Alice in the wonderland"
         },
         {
            "label":"christtree",
            "value":"The Christmas Tree"
         }
      ]
   },
   {
      "country":"TH",
      "language":"en",
      "localeBooks":[
         {
            "label":"matrix",
            "value":"The Matrix"
         }
      ]
   }
]

我通过countrylanguage 尝试了Collectors.groupingBy,但似乎它会产生类似关注的东西,这不是我想要的。我怎样才能达到我想要的预期输出?

{
 "GB_en": [
     {
       "label": "alice"
       "value": "Alice in the wonderland" 
     },
     {
       "label": "christtree"
       "value": "The Christmas Tree" 
     }
 ]
}

【问题讨论】:

    标签: json spring-boot java-8 grouping


    【解决方案1】:

    您可以通过toMap 收集器和merge 函数来完成:

    list.stream().collect(Collectors.toMap(LocaleBook::getLocale,
                        lb -> new NewPoJo(lb.getLocale().getCountry(), lb.getLocale().getLanguage(),
      new ArrayList<>(Collections.singletonList(new KeyValuePair(lb.getBookId(), lb.getBookName())))),
                (a, b) -> {
                    a.getLocaleBooks().addAll(b.getLocaleBooks());
                    return a;
                }))
         .values();
    

    只是你应该重写Locale 类中的equalshashCode 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-08
      • 2018-05-19
      • 1970-01-01
      • 2018-11-13
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多