即时订购集

我有一个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>));

不用说它没有用,所以任何有其他想法的人都会非常感激。


杨__羊羊
浏览 158回答 3
3回答

ITMISS

您可以使用TreeSet并提供比较器TreeSet<myData> sorted = new TreeSet<>(Comparator.comparing(MyData::expDtTm));sorted.addAll(dataLocations);或按照CollectorJavadocs类中的描述为TreeSet以下内容创建您自己的收集器:Collector<Widget, ?, TreeSet<Widget>> intoSet =&nbsp; &nbsp; &nbsp;Collector.of(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TreeSet::new,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TreeSet::add,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(left, right) -> { left.addAll(right); return left; }&nbsp; &nbsp; &nbsp;);

ibeautiful

您可以尝试以下方法:public class Example {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; Comparator<String> stringComparator =&nbsp; &nbsp; &nbsp; Comparator.comparing((String x) -> x);&nbsp; &nbsp; Supplier<TreeSet<String>> supplier =&nbsp; &nbsp; &nbsp; () -> new TreeSet<>(stringComparator);&nbsp; &nbsp; Set<String> set = new HashSet<>(Arrays.asList("1", "3", "7", "2", "9", "4"));&nbsp; &nbsp; TreeSet<String> treeSet = set.stream()&nbsp; &nbsp; &nbsp; .collect(Collectors.toCollection(supplier));&nbsp; &nbsp; System.out.println(treeSet);&nbsp; }}将String类替换为您的String类。输出[1, 2, 3, 4, 7, 9]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java