![](/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.