I have made a class as follows:
class strVal{
double val;
String str;
}
Now I made an array of this class now I want to sort that array by strVal.val
. I want to know if there is any standard defined method in Java?
I have made a class as follows:
class strVal{
double val;
String str;
}
Now I made an array of this class now I want to sort that array by strVal.val
. I want to know if there is any standard defined method in Java?
Implement java.lang.Comparable interface, and use java.util.Arrays.sort(...) to sort an array of StrVal:
public class StrVal implements Comparable<StrVal> {
private double val;
private String str;
public StrVal(double val, String str) {
this.val = val;
this.str = str;
}
@Override
public int compareTo(StrVal o) {
return (int)(this.val - o.val);
}
public double getVal() {
return val;
}
public String getStr() {
return str;
}
}
To sort the array :
StrVal[] array;
...
Arrays.sort(array)
Collections.sort might help you. Use a List<strVal>
and then:
Collections.sort(list, comparator);
Some more code:
List<strVal> list = ...;
Collections.sort(list, new Comparator<strVal>()
{
@Override
public int compare(strVal o1, strVal o2)
{
return o1.val - o2.val;
}
});
Or if you don't want to use a List, use Arrays.sort(array, comparator)
.
You need to implement Comparator or Comparable interface and then call Collections.sort on the collection of obejects of your class strVal. Follow this tutorial for learning more about collections sorting:
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
now I made an array of this class now I want to sort that array by strVal.val.
You can implement a Comparator, override its compare() method and use Arrays.sort().
In case you use a List<strVal>
use Collections.sort().
If you think that the comparison of the class objects can be done only by its val
property and that property defines the natural ordering of the objects then your class can implement Comparable.
Comparator :
new Comparator<strVal>()
{
@Override
public int compare(strVal o1, strVal o2)
{
return o1.val - o2.val;
}
});
Comparable:
class strVal implements Comparable<strVal>{
double val;
String str;
@Override
public int compareTo(strVal o) {
return this.val - o.val;
}
}
P.s.: Please adhere to Java naming conventions.
You will have to implement the comparable interface for that and make your val field the field where the compare will take place.
More info here: http://www.javapractices.com/topic/TopicAction.do?Id=10
you need to implement Comparable-interface and use the sort methods of the collection
You should use the sort
method defined in the Arrays
utility class.
In order to sort according to your key you should either make your class implement Comparable
or provide a Comparator
.