Sorting tuple counts in Java
I'm building a class with string to integer mapping So if I have three apples, I will map apples to three
I need to write a class that sorts the names of objects by reducing numbers
So, if I have
(apple, 3) (orange, 2) (banana, 5)
I'll get (banana, 5), (apple, 3), (orange, 2)
I wonder if there is a course that can make my life easier, or how I will achieve it
thank you.
Solution
You should be able to put objects (apple, 3) (oranges, 2) (bananas, 5) in List, and then call Collections.. sort(yourlist). Then, you need to ensure that the declared object implements the comparable interface
For more information, visit http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
Suppose you claim that you object to
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 sort your list by making the following calls:
FruitAndCount fruitArray[] = { new FruitAndCount("Apples",new FruitAndCount("Oranges",2),new FruitAndCount("Bananas",5) }; List<FruitAndCount> fruit = Arrays.asList(fruitArray); Collections.sort(fruit);
Then you should have a sorted list of fruits