Ordering Set by Instant

  • A+
Category:Languages

I have a Java Set that I give information to:

Set<myData> dataLocations = getData(location); 

I would like to sort this Set I have tried a sortedSet and couldn't get it to work, so I tried this

dataLocations = dataLocations.stream().sorted(Comparator.comparing(myData -> myData.expDtTm)).collect(Collectors.toSet()); 

The only problem is that in the Java documentation it doesn't guarantee retaining any orders. So I tried this:

TreeSet<myData> sortedDataLocations = dataLocations.stream().sorted(Comparator.comparing(myData -> myData.expDtTm)).collect(Collectors.toCollection(TreeSet<myData>)); 

needless to say it didn't work so anyone that has any other ideas they would be much appreciated.

 


You can use TreeSet and provide a comparator

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

Or as described in Collector class Javadocs create your own collector for TreeSet:

Collector<Widget, ?, TreeSet<Widget>> intoSet =      Collector.of(          TreeSet::new,           TreeSet::add,          (left, right) -> { left.addAll(right); return left; }      ); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: