简体   繁体   中英

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. The factory class contains a variable named Time which has some value. I want to pass two instances of my class FACTORY like (FACTORY A, FACTORY B) to sort the data available. The below code is in swift. How can I implement the same in JAVA.

Code in 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.
After that, you start the sorting algorithm (with the method sorted((first, decond) -> [...]);
The java8's sorting algorithm work like that:
The algorithm call your Comparator (here the comparator is the lamba expression (first, 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

And finally you transform the Stream to a list with .collect(Collectors.toList());

I hope that I help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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