Counting sorting in java for tuples

I am creating a class that has string matching with integers. So if I have 3 apples, I will have 3 apples displayed.

I need to write a class that sorts the name of objects by decreasing the number.

So, if I have

(apples, 3) (oranges, 2) (bananas, 5)

I will get (bananas, 5), (apples, 3), (oranges 2)

I was wondering if there is a class there that will make my life easier or how I implement it.

Thank.

+3
source share
3 answers

(, 3) (, 2) (, 5) , Collections.sort( ). , Comparable.

http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

, ,

public class FruitAndCount implements Comparable<FruitAndCount> {
    private final String name;
    private final Integer count;

    public FruitAndCount(String name, int count) {
        this.name = name;
        this.count = count;
    }

    public String name() { return name;  }
    public int count()   { return count; }

    public int compareTo(FruitAndCount o) {
        return this.count.compareTo(o.count);
    }
}

, :

FruitAndCount fruitArray[] = {
    new FruitAndCount("Apples", 3),
    new FruitAndCount("Oranges", 2),
    new FruitAndCount("Bananas", 5)
};

List<FruitAndCount> fruit = Arrays.asList(fruitArray);
Collections.sort(fruit);

.

+6

Comparable, (, -, ).

Collections.sort(), List<T> a Comparator<T>, , . , , Comparable ( ).

+4

TreeMap.

, , , . TreeMap , , . , .

If you have non-unique accounts, there is a simple solution here that will allow you to use TreeMap.

+2
source

Source: https://habr.com/ru/post/1729741/


All Articles