简体   繁体   中英

How to sort a Collection of Objects?

I have a class Gym which contains the following fields:

private int id;

private String name;

private String street;

private String housenumber;

private String zipcode;

private String lat;

private String lng;

private String city;

All of the data is in a database. A user can filter gyms by some creteria: sports and distance. I have a function which gets all of the gyms out of the database and adds them to a layout.

The lat and lng fields also are in the database.

When a user requests all the gyms the distance between the user and the position is calculated using the following code:

double distance = Math.round(gpsHelper.calculateDistance(location.getLatitude(), Double.valueOf(gym.getLat()),
                location.getLongitude(), Double.valueOf(gym.getLng()), 0.0, 0.0));
 DecimalFormat df = new DecimalFormat("#.##");
String formattedDistance = "Afstand: " + String.valueOf(df.format(distance)) + " km";

What I would like to do is the following: I would like to sort all the gyms by their distance to the user. So sort them by df.format(distance) .

Could anyone give me a push into the right direction? I think I've added al the relevant code.

Collections.sort

Collections.sort(List<T> list) sorts the specified list into ascending order, according to the natural ordering of its elements.

For example:

List<String> fruits = new ArrayList<String>();

fruits.add("Pineapple");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");

Collections.sort(fruits);

int i=0;
for(String temp: fruits){
    System.out.println("fruits " + ++i + " : " + temp);
}

Will give as output:

fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple

See other examples at: Java object sorting example (Comparable and Comparator) .

Comparator

Comparator is a comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort ) to allow precise control over the sort order.

Collections.sort(people, new Comparator<Person>() {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getLastName().compareTo(o2.getLastName());
    }
});

Lambda Expressions

Java 8 introduced Lambda Expressions and the Comparator 's equivalent is:

Comparator<Person> people =
    (Person o1, Person o2)->o1.getLastName().compareTo(o2.getLastName());

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