简体   繁体   English

如何在JAVA中一次传递一个类的两个单独实例来对该类中的某些数据进行排序

[英]How to pass two separate instances of a class at a time in JAVA to sort some data in that classes

I have a class called FACTORY. 我有一个名为FACTORY的课程。 The factory class contains a variable named Time which has some value. 工厂类包含名为Time的变量,该变量具有一些值。 I want to pass two instances of my class FACTORY like (FACTORY A, FACTORY B) to sort the data available. 我想传递我的类FACTORY的两个实例,如(FACTORY A,FACTORY B)来对可用数据进行排序。 The below code is in swift. 下面的代码很快。 How can I implement the same in JAVA. 我怎样才能在JAVA中实现相同的功能。

Code in Swift 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
            }

''' “””

Here's an example of how to sort the factories by the value of their time. 这是一个如何根据时间值对工厂进行排序的示例。

List<Factory> sortedFactories = factories.stream().sorted((first, second) -> {
            final long time1 = first.getTime();
            final long time2 = second.getTime();
            return time1-time2;
        }).collect(Collectors.toList());

How does it work: 它是如何工作的:
In the first line, your tranform theList factories to a java8 Stream class. 在第一行中,您将theList工厂转换为java8 Stream类。
After that, you start the sorting algorithm (with the method sorted((first, decond) -> [...]); 之后,启动排序算法(方法排序((first,decond) - > [...]);
The java8's sorting algorithm work like that: java8的排序算法就是这样的:
The algorithm call your Comparator (here the comparator is the lamba expression (first, decond) -> {...}); 算法调用你的比较器(这里比较器是lamba表达式(第一个,decond) - > {...});
And your comparator must return: 你的比较器必须返回:

A negative integer, zero, or a positive integer as the
first argument is less than, equal to, or greater than the
second.

And your list is sorted magically :D 你的清单神奇地排序:D

And finally you transform the Stream to a list with .collect(Collectors.toList()); 最后,使用.collect(Collectors.toList())将Stream转换为列表;

I hope that I help you. 我希望我帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM