How can I sort an array in Java/Android alphabetically?
After that I want to provide the ordered array to a ListView.
Arrays.sort() should do the trick
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
it can be done just using
Arrays.sort(myarray);
For more complex sorting see Comparator
Example:
Arrays.sort(some_array, new Comparator<SomeObject>() {
#Override
public int compare(SomeObject entry1, SomeObject entry2) {
return entry1.getSomeData().compareTo(entry2.getSomeData());
}
});
Objects that implement the Comparable interface (like Strings) have a natural ordering (as defined by its compareTo method) so you can just use Arrays.sort():
Arrays.sort(yourArrayOfComparables);
It will directly sort the array and will not make a copy.
If you want a more specific sort that isn't considered "natural" you can create a Comparator for that object:
Comparator<MyObject> comp = new Comparator<MyObject>() {
public int compare(MyObject obj1, MyObject obj2) {
//Code here
}
}
Arrays.sort(yourArrayOfObjects, comp);
The rules for Comparators and Comparables (where the first object is the object itself) is: return a negative if the first object is less than the second, positive for the other way round and 0 if they're equal.
Related
Consider this arraylist with linkedlist objects
(are->1->3->7 , croco-> 4 ->1 , bat ->3->8).
Now I have to sort the arraylist in java in ascending order considering the first element of linkedlist contained in arraylist.
There is a method Collections.sort() but it is useful when objects are strings.
What to apply in this situation?
The final list should look something like this
(are->1->3->7 , bat ->3->8 , croco-> 4 ->1 )
Collections.sort(); has an overloaded method that takes a comparator as well. So you want something like this:
Collections.sort(lists, (o1, o2) ->
o1.get(0).compareTo(o2.get(0))
);
Or if you can use Java 8, there is a default sort method in List interface:
lists.sort(Comparator.comparing(o -> o.get(0)));
Without much context, I might be wrong. However, from my judgement if you're using your own objects which contain an identifier (are, croco and bat), and a linkedlist(numbers), then you can use the following solution.
Your class needs to implement the Comparable Interface
You need to override the compareTo() method
Collections.sort() should sort your objects in ascending order.
public class Example implements Comparable {
private String identifier;
private List<Integer> list;
// constructors
// getters
#Override
public int compareTo(Object other){
if(this.list.head() > other.list.head()) return 1;
if(this.list.head() < other.list.head()) return -1;
else return 0;
}
}
I'm a C# developer trying to work on Java. I'm stuck in creating a dynamic comparator. below is the code
public class SortImpl implements Sort {
public SortImpl() {
}
public ArrayList<Comparable> sort(ArrayList<Comparable> var1) {
Comparator var2 = new Comparator() {
};
var1.sort(var2);
return var1;
}
}
But Comparator needs a type while creating a Comparator object. My ArrayList can be of any type like int, double, float. Please let me know what I am doing wrong.
As I can understand from your code snippet you trying to create sort implementation, not comparator itself.
A Comparator<T> is an object that compare two objects.
From JavaDoc:
int compare(T o1, T o2)
Compares its two arguments for order.
Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Because list elements already Comparable they can be directly compared as o1.compareTo(o2).
Also sort should be defined as public <T extends Comparable> List<T> sort(List<T> var1).
You don't need to implement a Comparator at all if you use java.util.Collections for sorting the list: it will then be sorted according to the natural ordering of its elements:
public ArrayList<Comparable> sort(ArrayList<Comparable> var1) {
Collections.sort(var1);
return var1;
}
In Java you dont have to implement Comparators for those types (Integer, Float, Char, String, etc...) When you define a List, you will say what type it is:
List<Person> list = new ArrayList<Person>();
When you sort the list, you may use the Collections.sort(List list, Comparator comparator) method. You may invoke it like:
Collections.sort(list, new Comparator<Person>() {
public int compare(Personobject1, Personobject2) {
return 0;//Put your code here
}
});
Parameters:
o1 - the first object to be compared.
o2 - the second object to be compared.
Returns:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
See https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html for more information
In my java program i have created a Vector of user defined type
Vector<PolledData> poll=null;. The Vector is of type of instance of class PolledData.
I need to sort the Vector poll, I tried Collections.sort(poll);,but it didn't work.
Is there a any way to sort the vector poll?
The Solution is:
Collections.sort(poll, new Comparator<PolledData>() {
#Override
public int compare(final PolledData object1, final PolledData object2) {
return object1.getName().compareTo(object2.getName());
}
} );
Now the elements in my Vector poll is sorted.
You need to implement Comparable / Compactor for pojo which are being stored in vector.
This question already has answers here:
Sorting an ArrayList of objects using a custom sorting order
(12 answers)
Closed 8 years ago.
I want to sort this list of Emp objects in ascending order based on the marks field.
List<Emp> emp= new ArrayList<Emp>();
public class Emp implements Serializable {
private String empname;
private String section;
private int empId;
private int marks;
...
You need to write a comparator, otherwise the Sort method assumes which fields you want use when sorting.
Collections.sort(emp, new Comparator<Emp>() { public int compare(Emp one, Emp two) {
return one.marks.compareTo(two.marks);
});
In my example i treated the field marks as public, replace one.marks with a getter if you so choose.
Also since you're using ints which do not have a compareTo, do like so:
Collections.sort(list, new Comparator<Emp>() {
public int compare(Emp one, Emp two) {
int cmp = one.getMarks() > two.getMarks() ? +1 : one.getMarks() < two.getMarks() ? -1 : 0;
return cmp;
}
});
You can use a comparator object to sort.
Collections.sort();
does the sorting.
This will work with your List. The method to be used is compareTo.
if (list.size() > 0) {
Collections.sort(list, new Comparator<Emp>() {
#Override
public int compare(final Emp object1, final Emp object2) {
return object1.getMarks().compareTo(object2.getMarks());
}
} );
}
There are two main ways of supporting object comparisons in Java.
You can have your class implement the Comparable interface, which is acceptable when your objects have a natural ordering that you're relying on (for example, alphabetical ordering for strings). This requires classes to implement a compareTo method which defines the comparison rule between instances.
The standard alternative is to instantiate a Comparator for your class, and specify the comparison rule in a compare method.
In your case, the latter option seems more appropriate. The mechanics of the compare method are fairly simple: it takes two instances of your class, returns a negative value if the first is "less than" the second, a positive number if it is "greater", and 0 if they are "equal". For integer-based comparisons, like comparing by marks, the quick trick is to return the difference of the numbers.
Once you have your Comparator defined, sorting is as simple as invoking the Collections.sort method, opting for the method signature which takes a List and a specified Comparator.
List<Emp> emps = new ArrayList<Emp>();
// populate list...
Comparator<Emp> empComparator = new Comparator<Emp>() {
public int compare(Emp e1, Emp e2) {
return e2.getMarks() - e2.getMarks();
}
};
Collections.sort(emps, empComparator);
As the title suggests, I have a list consisting of pairs of integers (int ai and int bi). I want to sort this list based on only upon int a, while preserving the pairwise relationship. I was wondering if there was an efficient way to do this with some of the standard libraries Java has. Thanks in advance!
Edit:
My exact implementation is an ArrayList<ArrayList<Integer>> in which each ArrayList<Integer> has exactly two integers (ai and bi). Sorry for any confusion.
Use the Collections sort() or Arrays sort() method which takes a Comparator and use a custom comparator which only inspects the first integer in the pair.
Something like this (roughly, depending on your exact types):
Collections.sort(myList, new Comparator<IntegerPair>() {
#Override public int compare(IntegerPair x, IntegerPair y) {
return x.first - y.first;
}
});
Since the sorting algorithms are stable (per the Javadocs) your list will be sorted per your description.
Implement http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html for your integer pairs and use sort() from http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html
I would recommend to create a class that represents integer pair. This class should implement Comparable. The use sort() to sort it.
It may be a little safer to use the already-defined Integer compare:
Collections.sort(myList, new Comparator<IntegerPair>() {
#Override public int compare(IntegerPair x, IntegerPair y) {
return Integer.compare(x.first, y.first);
}
});