How can I create a list (or some other type of container) of integer and strings pairs that allows duplicates in both pairs and can be sorted by the integer value?
I need to fill a container with names (string) and scoring (integer) pairs, the container must allow duplicated values in both name and scoring, and i need to sort this list by the scoring value.
I tried with a SortedMap but doesn't allow duplicated values:
SortedMap<Integer,String> sm=new TreeMap<Integer, String>();
sm.put(23, "Peter");
sm.put(11, "Tony");
sm.put(110, "Claire");
sm.put(13, "ferca");
sm.put(55, "Julian");
sm.put(13, "Pedro");
In this example, ferca and Pedro have the same scoring value, this is something I need to allow, but the SortedMap overwrites "ferca" with "Pedro".
What is the best container type to do this?
Approach: Store the pairs in an array using a user-defined Pair class. Override the comparator method to sort the array according to the first element. Sort the array according to the first element.
Summary. Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.
Sort String in Java There is no direct method to sort a string in Java. You can use Arrays, which has a method CharArray() that will create a char input string and using another method (Arrays. sort(char c[]) , we can easily sort.
Since you want your collection to be ordered, I suggest you use a List
and Collections.sort
. If you decide to go for this approach you still have two options:
Comparator
that can be passed as an argument to sort
, orScore
class implement Comparable<Score>
Here is an example and ideone demo of the latter approach:
import java.util.*;
class Score implements Comparable<Score> {
int score;
String name;
public Score(int score, String name) {
this.score = score;
this.name = name;
}
@Override
public int compareTo(Score o) {
return score < o.score ? -1 : score > o.score ? 1 : 0;
}
}
public class Test {
public static void main(String[] args){
List<Score> scores = new ArrayList<Score>();
scores.add(new Score(23, "Peter"));
scores.add(new Score(11, "Tony"));
scores.add(new Score(110, "Claire"));
scores.add(new Score(13, "ferca"));
scores.add(new Score(55, "Julian"));
scores.add(new Score(13, "Pedro"));
Collections.sort(scores);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With