Hello Friends, Today i am going to post use of Collection class in android for manipulate data Like Sorting.
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import android.app.Activity;
import android.os.Bundle;
public class TestActivity extends Activity {
/** Called
when the activity is first created. */
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String>
ar_hb = new ArrayList<String>();
//Add elements
to Arraylist
ar_hb.add("Hasmukh");
ar_hb.add("Bhadani");
ar_hb.add("Samir");
ar_hb.add("BJgroup");
//sorting
function
Collections.sort(ar_hb);
//display
elements of ArrayList
System.out.println("ArrayList
elements after sorting in ascending order : ");
System.out.println(Arrays.toString(ar_hb.toArray()));
System.out.println("ArrayList
elements Comparing - ignorecase");
IgnoreCaseComparator
icc = new IgnoreCaseComparator();
java.util.Collections.sort(ar_hb,icc);
Collections.sort(ar_hb);
System.out.println(Arrays.toString(ar_hb.toArray()));
System.out.println("Reversing
the ArrayList");
Collections.sort(ar_hb,
Collections.reverseOrder());
System.out.println(Arrays.toString(ar_hb.toArray()));
}
class IgnoreCaseComparator
implements Comparator<String>
{
public int compare(String
strA, String strB) {
return
strA.compareToIgnoreCase(strB);
}
}
}
here is the another example:
More Ref Link:
here is the another example:
suppose we have array list of User
User class have following params
param :
uid
name
address
suppose ArrayList<User> users has many values and we want it to sory by name then use following code.
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
return u1.name.compareToIgnoreCase(u2.name);
}
});
above code will sort users array by name.
More Ref Link:
I
will be happy if you will provide your feedback or follow this blog. Any suggestion
and help will be appreciated.
Thank
you :)
No comments:
Post a Comment