I have a hashmap with a triplet like this:
HashMap<String, List<Triplet<String,Integer,Integer>>> output = new HashMap<String, List<Triplet<String,Integer,Integer>>>();
Where the key is a file name and triplet contains information of a word and its frequency information(tf and df).Eg
{File1 = {coffee,23,1},{caffeine,12,2},{brew,9,1}; File2 = {}.......}
I want to sort the values of this list of triples according to the second value of the triplet ie tf (term frequency).
for (Entry<String, List<Triplet<String, Integer, Integer>>> entry : output.entrySet()) {
String key = entry.getKey();
List<Triplet<String, Integer, Integer>> value = entry.getValue();
What will come next?
Here's what Triplet looks like:
public class Triplet<T, U, V> {
private final T first;
private final U second;
private final V third;
public Triplet(T first, U second, V third) {
this.first = first;
this.second = second;
this.third = third;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
public V getThird() {
return third;
}
}
Any help, guidance will be appreciated.
There are 2 ways than came into my mind:
make your Triplet
Comparable
write a Comparator
Than you can either sort the List or use eg a TreeSet
If you can not change your Triplet
class by implementing Comparable
on it, this would be a solution, using the Collections.sort
method:
for (Entry<String, List<Triplet<String, Integer, Integer>>> entry : output.entrySet()) {
String key = entry.getKey();
List<Triplet<String, Integer, Integer>> value = entry.getValue();
// This sorts the list using the anonymous instantiated Comparator class
Collections.sort(value, new Comparator<Triplet<String, Integer, Integer>>(){
@Override
public int compare(Triplet<String, Integer, Integer> object1, Triplet<String, Integer, Integer> object2) {
return object1.getSecond().compareTo(object2.getSecond());
}
});
Or, in a more generic way, without using hard types:
Collections.sort(value, new Comparator<Triplet>(){
@Override
public int compare(Triplet object1, Triplet object2) {
return object1.getSecond().compareTo(object2.getSecond());
}
});
What about this?
public class Triplet<T, U, V> implements Comparable<Triplet<T, U, V> > {
private final T first;
private final U second;
private final V third;
public Triplet(T first, U second, V third) {
this.first = first;
this.second = second;
this.third = third;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
public V getThird() {
return third;
}
public int compareTo(Triplet<T, U, V> comparetrpl) {
T a = comparetrpl.getFirst();
//ascending order
return (this.first > a) ? 1 : 0;
//descending order
//return (a > this.first) ? 1 : 0;
}
}
And the use sort
method?
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.