Java – list sorting challenges
•
Java
Suppose I have
final Iterable<String> unsorted = asList("FOO","BAR","PREFA","ZOO","PREFZ","PREFOO");
What can I do to convert this unordered list to:
[PREFZ,PREFA,BAR,FOO,PREFOO,ZOO]
(list starting with known values that must appear first (here "prefa" and "prefz"), the rest are sorted alphabetically)
I think there are some useful classes in guava that can do this (ordering, predictions...), but I haven't found a solution yet
Solution
You mentioned guava in particular; Together with Sylvain M's answer, this is another way (more like an academic exercise and a demonstration of guava flexibility than any other way)
// List is not efficient here; for large problems,something like SkipList // is more suitable private static final List<String> KNowN_INDEXES = asList("PREFZ","PREFA"); private static final Function<Object,Integer> POSITION_IN_KNowN_INDEXES = new Function<Object,Integer>() { public Integer apply(Object in) { int index = KNowN_INDEXES.indexOf(in); return index == -1 ? null : index; } }; ... List<String> values = asList("FOO","PREFOO"); Collections.sort(values,Ordering.natural().nullsLast().onResultOf(POSITION_IN_KNowN_INDEXES).compound(Ordering.natural()) );
In other words, press list Indexof() returns the natural order of integers, and then breaks the relationship with the natural order of the object itself
It may be messy, but it's interesting
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码