![](/img/trans.png)
[英]Java: how to create instances of two different classes in a third class and pass references to each other through the constructors
[英]How to pass two separate instances of a class at a time in JAVA to sort some data in that classes
我有一个名为FACTORY的课程。 工厂类包含名为Time的变量,该变量具有一些值。 我想传递我的类FACTORY的两个实例,如(FACTORY A,FACTORY B)来对可用数据进行排序。 下面的代码很快。 我怎样才能在JAVA中实现相同的功能。
Swift中的代码
“””
self.factories = self.factories.sorted { (first: FACTORY, second: FACTORY) in
var times = [first.Time]
var firstDate: Time? = nil
for time in times {
if let dateFromTime = DateFormatter.iso8601TimeFormatter.date(from: time) {
}
}
times = [second.Time]
var secondDate: Time? = nil
for time in times {
if let dateFromTime = DateFormatter.iso8601TimeFormatter.date(from: time) {
}
}
if firstDate != nil && secondDate != nil {
return firstDate! < secondDate!
}
return false
}
“””
这是一个如何根据时间值对工厂进行排序的示例。
List<Factory> sortedFactories = factories.stream().sorted((first, second) -> {
final long time1 = first.getTime();
final long time2 = second.getTime();
return time1-time2;
}).collect(Collectors.toList());
它是如何工作的:
在第一行中,您将theList工厂转换为java8 Stream类。
之后,启动排序算法(方法排序((first,decond) - > [...]);
java8的排序算法就是这样的:
算法调用你的比较器(这里比较器是lamba表达式(第一个,decond) - > {...});
你的比较器必须返回:
A negative integer, zero, or a positive integer as the
first argument is less than, equal to, or greater than the
second.
你的清单神奇地排序:D
最后,使用.collect(Collectors.toList())将Stream转换为列表;
我希望我帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.