[英]How can I use lambda expressions in a Comparator class in Java
I am fairly new to Java and now I have to create some Comparator classes. 我是Java的新手,现在我必须创建一些Comparator类。
On this Stackoverflow page I have found some really useful information about using lambda expressions. 在这个Stackoverflow页面上,我发现了一些关于使用lambda表达式的非常有用的信息。 How to compare objects by multiple fields
如何通过多个字段比较对象
Which made me thing about creating a Compartor class like this: 这让我有关创建这样的Compartor类的事情:
public class WidthComparator implements Comparator{
@Override
public int compare(Object t, Object t1) {
Foto foto1 = (Foto)t;
Foto foto2 = (Foto)t1;
return Comparator.comparing(Foto::getWidth)
.thenComparing(Foto::getHeight)
.thenComparingInt(Foto::getName);
}
}
}
so when I have a collection called fotosCollection, I would like to be able to do this: 所以当我有一个名为fotosCollection的集合时,我希望能够这样做:
fotosCollection.sort(new HoogteComparator());
This obviously does not work, but how could I get this to work? 这显然不起作用,但我怎么能让它工作?
Ps. PS。 I have to use a Comparator class.
我必须使用Comparator类。
Comparator.comapring
returns a Comparator
- you can just use it directly: Comparator.comapring
返回一个Comparator
- 您可以直接使用它:
// Define a "constant" comparator
private static final Comparator<Foo> HOOGTE_COMPARATOR =
Comparator.comparing(Foto::getWidth)
.thenComparing(Foto::getHeight)
.thenComparingInt(Foto::getName);
// Use it elsewhere in your code
fotosCollection.sort(HOOGTE_COMPARATOR);
If you really don't want the comparator type to be anonymous for some reason, you can do: 如果由于某种原因你真的不希望比较器类型是匿名的,你可以这样做:
public class WidthComparator implements Comparator<Foto>{
private final static Comparator<Foto> FOTO_COMPARATOR = Comparator.comparing(Foto::getWidth)
.thenComparing(Foto::getHeight)
.thenComparingInt(Foto::getName);
@Override
public int compare(Foto foto1, Foto foto2) {
return FOTO_COMPARATOR.compare(foto1, foto2);
}
}
I also would consider avoiding the use of the rawtype and implement Comparator<Foto>
instead, as I did above. 我也会考虑避免使用rawtype并实现
Comparator<Foto>
,就像我上面所做的那样。
You can try this old-style approach: 你可以尝试这种旧式的方法:
public class WidthComparator implements Comparator{
@Override
public int compare(Object t, Object t1) {
Foto foto1 = (Foto)t;
Foto foto2 = (Foto)t1;
// width asc order
if(foto1.getWidth() != foto2.getWidth())
return foto1.getWidth() - foto2.getWidth();
// height asc order
if(foto1.getHeight() != foto2.getHeight())
return foto1.getHeight() - foto2.getHeight();
// name asc order
return foto1.getName().compareTo(foto2.getName());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.