Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting sort in java for tuples

I am building a class that has a mapping of strings to integers. So if I have 3 apples I would have a mapping of apples to 3.

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

So if I have

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

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

I was wondering if there's already a class out there that would make my life easier or how I would implement this.

Thanks.

like image 547
SuperString Avatar asked May 17 '26 23:05

SuperString


1 Answers

You should be able to put your objects (apples, 3) (oranges, 2) (bananas, 5) into a List and then call Collections.sort(yourlist). You'd then want to make sure the object you declared implements the Comparable interface.

More information is available at http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

Let's say you declared you object as

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);
    }
}

You should then be able to make the following call which will sort your list:

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

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

You should then have a sorted list of fruit.

like image 146
Brian Hasden Avatar answered May 20 '26 17:05

Brian Hasden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!