Java:可比较<;列表<;T扩展可比较<;T>&燃气轮机&燃气轮机;
Java中是否有Java:可比较<;列表<;T扩展可比较<;T>&燃气轮机&燃气轮机;,java,comparable,Java,Comparable,Java中是否有可比较的实现(其行为类似于C++的std::list::operator,我不知道,但编写起来应该不会太难 compareTo(Collection<T> other) { Iterator<T> i1 = this.iterator(); Iterator<T> i2 = other.iterator(); while(i1.hasNext() && i2.hasNext()) { in
可比较的实现(其行为类似于C++的std::list::operator,我不知道,但编写起来应该不会太难
compareTo(Collection<T> other) {
Iterator<T> i1 = this.iterator();
Iterator<T> i2 = other.iterator();
while(i1.hasNext() && i2.hasNext()) {
int c = i1.next().compareTo(i2.next());
if(c != 0) {
return c;
}
}
if(i1.hasNext()){
return 1;
} else if(i2.hasNext()) {
return -1;
} else {
return 0;
}
}
比较(集合其他){
迭代器i1=this.Iterator();
迭代器i2=other.Iterator();
while(i1.hasNext()&&i2.hasNext()){
int c=i1.next().compareTo(i2.next());
如果(c!=0){
返回c;
}
}
if(i1.hasNext()){
返回1;
}else if(i2.hasNext()){
返回-1;
}否则{
返回0;
}
}
> p>我不知道你提到的C++运算符,但是我假设你想要的是一个比较器,它比较字典的集合。
通过其出色的排序
类:
返回一个新的排序,该排序通过成对比较相应的元素对iterables进行排序,直到找到一个非零的结果;强制使用“字典顺序”。如果到达一个可数的末尾,但未到达另一个,则认为较短的可数小于较长的可数。例如,整数的字典自然排序考虑[]<[1]<[1,1]<[1,2]<[2]
假设您想根据字符串的自然顺序订购列表
:
List<List<String>> lists = ...;
Ordering<Iterable<String>> comparator = Ordering.natural().lexicographical();
Collections.sort(lists, comparator);
我应该指出,这只适用于有序集合。例如,它不适用于基于哈希表的集合,因为哈希表迭代器返回的元素顺序取决于构造该表的操作序列。
/*
* This comparator will use a case insensitive comparison of individual
* strings in determining the ordering.
*/
Ordering<Iterable<String>> comparator =
Ordering.from(String.CASE_INSENSITIVE_ORDER).lexicographical();
/*
* This comparator uses a Function<Foo, Long> (Foo.GET_ID) to compare the IDs
* of Foo instances.
*/
Ordering<Iterable<Foo>> comparator =
Ordering.natural().onResultOf(Foo.GET_ID).lexicographical();