【问题标题】:How to change a list of lists into a list如何将列表列表更改为列表
【发布时间】:2022-01-11 09:26:52
【问题描述】:

是否有 lambda 表达式,或者 java 内置的东西 将列表列表更改为一个列表。

例如 -->

public List<LocalDateTime> getallsort(){

    List<LocalDateTime> elite = getElite(true);
    List<LocalDateTime> recreation = getRecreation(true);
    List<LocalDateTime> youth = getYouth(true);
    List<List<LocalDateTime>> list = Arrays.asList(elite,recreation,youth);
    list.sort((xs1, xs2) -> xs1.size() - xs2.size());
    return list. ????? 
}

有没有一种奇特的方法可以将所有列表返回到 1 个列表中? 我无法使用这些关键字在堆栈上找到此问题。

【问题讨论】:

标签: java collections java-stream


【解决方案1】:
public List<LocalDateTime> getallsort(){
  List<LocalDateTime> elite = getElite(true); 
  List<LocalDateTime> recreation = getRecreation(true);
  List<LocalDateTime> youth = getYouth(true);
  List<List<LocalDateTime>> list = Arrays.asList(elite,recreation,youth);
  list.sort((xs1, xs2) -> xs1.size() - xs2.size());
  return list.stream().flatMap(List::stream).collect(Collectors.toList());
}

它回答了您关于将List&lt;List&lt;&gt;&gt; 转换为扁平化List&lt;&gt; 的原始问题。

甚至

public List<LocalDateTime> getallsort(){
  return Stream.of(
    getElite(true),
    getRecreation(true),
    getYouth(true)
    )
    .sorted((xs1, xs2) -> xs1.size() - xs2.size())
    .flatMap(List::stream)
    .collect(Collectors.toList());
}

这适用于您的原始示例,但可能不能直接回答您的问题。

【讨论】:

  • 这个答案不再有价值,因为这是其他原始问题的副本。 - 左答案使用Stream.of
  • 还是谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多