为了账号安全,请及时绑定邮箱和手机立即绑定

即时订购集

即时订购集

杨__羊羊 2021-05-07 14:11:43
我有一个Java Set,可以向以下人员提供信息:Set<myData> dataLocations = getData(location);我想对这个Set进行排序,但是我尝试了sortedSet却无法使其正常工作,所以我尝试了dataLocations = dataLocations.stream().sorted(Comparator.comparing(myData -> myData.expDtTm)).collect(Collectors.toSet());唯一的问题是,在Java文档中,它不能保证保留任何订单。所以我尝试了这个:TreeSet<myData> sortedDataLocations = dataLocations.stream().sorted(Comparator.comparing(myData -> myData.expDtTm)).collect(Collectors.toCollection(TreeSet<myData>));不用说它没有用,所以任何有其他想法的人都会非常感激。
查看完整描述

3 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

您可以使用TreeSet并提供比较器


TreeSet<myData> sorted = new TreeSet<>(Comparator.comparing(MyData::expDtTm));

sorted.addAll(dataLocations);

或按照CollectorJavadocs类中的描述为TreeSet以下内容创建您自己的收集器:


Collector<Widget, ?, TreeSet<Widget>> intoSet =

     Collector.of(

         TreeSet::new, 

         TreeSet::add,

         (left, right) -> { left.addAll(right); return left; }

     );


查看完整回答
反对 回复 2021-05-26
?
ibeautiful

TA贡献1993条经验 获得超6个赞

您可以尝试以下方法:


public class Example {

  public static void main(String[] args) {

    Comparator<String> stringComparator =

      Comparator.comparing((String x) -> x);


    Supplier<TreeSet<String>> supplier =

      () -> new TreeSet<>(stringComparator);


    Set<String> set = new HashSet<>(Arrays.asList("1", "3", "7", "2", "9", "4"));

    TreeSet<String> treeSet = set.stream()

      .collect(Collectors.toCollection(supplier));

    System.out.println(treeSet);

  }

}

将String类替换为您的String类。


输出


[1, 2, 3, 4, 7, 9]


查看完整回答
反对 回复 2021-05-26
  • 3 回答
  • 0 关注
  • 157 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号