I want to sort my Listview according to some value in my application but i dont know how to code it. I researched and found that people are using comparator and collection to sort the arraylist. Basically, i want to sort by some status such as accepted or rejected. The value is store in TAG_ACCEPT_REJECT and display in R.id.applicantStatus.
Below is my code:
adapter = new SimpleAdapter(
ApplicantJobStatusActivity.this,
applicantsList,
R.layout.list_applicant_status,
new String[] { TAG_UID, TAG_NAME,
TAG_ACCEPT_REJECT,
TAG_ACCEPT_REJECT_DATETIME },
new int[] { R.id.applicantUid,
R.id.applicantName,
R.id.applicantStatus,
R.id.accept_reject_datetime });
setListAdapter(adapter);
I want to know how and where to place the sorting code using comparator and collection to rearrange my ListView.
You should sort your list applicantsList prior to passing it to your adapter. You can then use the Collections.sort approach. Something like that:
Collections.sort(applicantsList, new Comparator<T extends Map<String, ?>> {
public int compare(T map1, T map2) {
if (!map1.has(TAG_ACCEPT_REJECT)) return -1;
if (!map2.has(TAG_ACCEPT_REJECT)) return 1;
// Assumes the objects you store in the map are comparables
return map1.get(TAG_ACCEPT_REJECT).compareTo(map2.get(TAG_ACCEPT_REJECT));
}
});
- Use Arrays.sort() before assigning the Array to the Adapter.
- Or you can Use Collections.sort(Collection c) with Comparable Interface,
- Or Collections.sort(Collection c, Comparator cp) with Comparator Interface, with Colletions like ArrayListbefore assigning it to theAdapter`.
///////////////////////// Edited Part//////////////////////////
See this below link, which contains all the examples of sorting an Array, ArrayList etc using various techniques.
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Related
The below image will show the code for that drop down box. It will return a list of object, after that I'm creating new SelectItem object. Is there any way to sort the list of object before I'm creating new SelectItem object.
Sorry, I'm not able to send the entire code, due to confidential
Use Collections.sort(..). If your want to sort particular field of your object, then you need to implements your own Comparator. See sample
Collections.sort(yourList,new Comparator<Object>() {
public int compare(Object obj1,Object obj2) {
return ((YourObject) obj1).getName().compareTo(((YourObject) obj2).getName);
}
});
Or you can simply uses as default sorting
Collections.sort(list, Collections.sort(list);
Lets say I have an array of an array of strings:
ArrayList<ArrayList<String>> arrayOfArray= new ArrayList<ArrayList<String>>();
Maybe it could look something like this(eg.):
arrayOfArray = [[A,1,B,2],[C,1,D,2],[C,1,D,2],[A,1,B,2]]
In the end I want this(duplicates was removed):
arrayOfArrayNoDuplicates = [[C,1,D,2],[A,1,B,2]]
Then as a final step I want this array of array to be sorted on the first item in the array.
Looks like this array of array maybe was sorted on the A or the B.
arrayOfArraySorted = [[A,1,B,2],[C,1,D,2]]
Is this possible without also sorting the inner array? I want to keep the order within the array "A,1,B,2".
I hope you understand want I want to do:)
/M
You use a set
It functions like an array, it dedupes
You can use a Set with a Comparator fot that.
Set<List<String>> list = new TreeSet<ArrayList<String>>(
new Comparator<List<String>>() {
public int compare(List<String> left, List<String> right) {
//check here if equal, before or after...
}
}
);
You should really use a HashSet or similar to remove duplicates from your collection of data (sets can only contain unique elements). I'm unsure how effective this will be against ArrayList's of varying contents though, so you might be best off extending ArrayList<String> and implementing your own bool equals(Object a) method (for your inner arrays).
To then sort your collection you should using Collections.sort(), you can then pass this a custom Comparator to sort them by whichever order you please. (A comparator lets you provide a method that takes 2 objects and rates their order.) Or if you've extended ArrayList<String> simply add the compare method to your class and add implements Comparator.
An example Comparator would be;
import java.util.*;
class ALComparator implements Comparator<ArrayList<String>>
{
#Override
public int compare(ArrayList<String> a, ArrayList<String> b)
{
if(a.size()==b.size())
return 1;
if(a.size()==0)
return -1;
if(b.size()==0)
return 1;
return a.get(0).compareTo(b.get(0));
}
}
I have this map:
Map<Integer,List<EventiPerGiorno>> mapEventi=new HashMap<Integer,List<EventiPerGiorno>>();
where EventiPerGiorno is a Comparable object.
How can I get a sorted list from the map?
I tried with
Collection<List<EventiPerGiorno>> collection=mapEventi.values()
Comparable.sort(collection);
But Comparable.sort() doesn't like the list as comparable. Is there a ComparableList?
EDIT
this is the comparable method...
public class EventiPerGiorno implements Comparable<EventiPerGiorno>{
#Override
public int compareTo(EventiPerGiorno o) {
return this.getPrimoSpettacolo().compareTo(o.getPrimoSpettacolo());
}
}
Java Collections don't have any order associated with them. You could turn the Collection into a List first and then sort it.
Collection<List<EventiPerGiorno>> collection = mapEventi.values()
YourComparableList<List<EventiPerGiorno>> list = new YourComparableList(collection);
Collections.sort(list);
For this, you will need to create some sort of List that implements Comparable. See How do I correctly implement Comparable for List in this instance? for an example.
Note that this is sorting the objects of type List<EventiPerGiorno>, not the objects of type EventiPerGiorno. If you are interested in sorting the latter, you might want this instead:
ArrayList<EventiPerGiorno> bigList = new ArrayList<EventiPerGiorno>();
for (List<EventiPerGiorno> list : mapEventi.values()) {
bigList.addAll(list);
}
Collections.sort(bigList);
You are attempting to sort a List of Lists. List doesn't implement Comparable. You'll have to create your own Comparator instance.
Map<String, List<EventiPerGiorno>> map = new HashMap<String, List<EventiPerGiorno>>();
List<List<EventiPerGiorno>> lists = new ArrayList(map.values());
Collections.sort(lists, new Comparator<List<EventiPerGiorno>>() {
#Override
public int compare(List<EventiPerGiorno> o1, List<EventiPerGiorno> o2) {
// ??? This is up to you.
return 0;
}
});
This will sort every list in your map:
for (List<EventiPerGiorno> list : mapEventi.values()) {
Collections.sort(list);
}
Or if you perhaps want to retrieve a single sorted list without modifying the lists in the map:
int someKey = ...;
List<EventiPerGiorno> list = new ArrayList<>(mapEventi.get(someKey));
Collections.sort(list);
return list;
You would need to extend List and make it implement Comparable. There is no default natural ordering that can be used to compare multiple Lists.
The collections framework wouldnt know if you wanted to sort the list by number of items, number of duplicates, or values within the list.
Then to sort you use:
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29
I've only started learning Java about 3 months ago and this is my first post here, so please bear with me.
I have multiple ArrayLists built from parsed XML that are directly related to each other in order. The arrays are later put into a single mapped ArrayList (groupData) to be read with a SimpleAdapter which creates the list in the Android GUI.
What I want to do is sort the list in alphabetical order based on one array (arr_title) and the other arrays stay in synchronized order to it. It doesn't matter where the sorting happens as long as the final displayed list is sorted. I expect it would be best to sort the mapped array once it's built. The simpler or easier to understand the code the better, but don't want the sorting to go very slow either. I have about 140 objects per array, but that could expand considering the XML is pulled from the web.
I've spent hours searching Google and tried a number of things with little progress. Collections.sort(arr_title) will sort the one array as I want it, but then the other arrays don't match up and doing the same thing to the other arrays obviously just sorts them individually as I don't want. I've noticed mention of using the TreeMap type and Comparator for similar sorting, but couldn't figure out how to use them in this case probably because the examples didn't provide a big enough picture for me to understand.
The sample below is where most of the stuff happens after the separate arrays are created.
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
Map<String, String> group;
int item = 0;
do {
group = new HashMap<String, String>();
group.put("title", arr_title.get(item));
group.put("desc", arr_desc.get(item));
group.put("num", Integer.toString(arr_num.get(item)));
groupData.add(group);
item++;
} while (item < arr_num.size());
SimpleAdapter adapter = new SimpleAdapter(this, groupData, android.R.layout.simple_list_item_2, new String[] {"title", "desc", "num"}, new int[]{android.R.id.text1, android.R.id.text2});
setListAdapter(adapter);
I tend to agree, using a comparator would be easier.
i.e.
Comparator<HashMap<String, String>> comparator = new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> object1, HashMap<String, String> object2)
{
return object1.get("title").compareToIgnoreCase(object2.get("title"));
}
};
Collections.sort(groupData, comparator);
'title' being the key in the hash to sort on.
Welcome to SO.
First of all, there are Java conventions to name the variables. Have a look at the Naming conventions
Secondly, Java is an Object Oriented Language, so you have to change your mind a little bit about how you approach problems.
In this particular case, you want all the data scattered among 3 arrays to be together. Well, create a class for it.
public class Data implements Comparable{
private String title;
private String desc;
private int num;
public Data(String title, String desc, int num){
//set the private fields here
}
//You may want to write some setters and getters here for individual fields.
public int compareTo(Object o){
//here you compare an item with other item. Remember to cast the object o to Data.
// Read http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html to know what to return
}
}
And then in your main class:
int item = 0;
do {
Data group = new Data(arr_title.get(item),arr_desc.get(item),arr_num.get(item);
groupData.add(group);
item++;
} while (item < arr_num.size());
Collections.sort(groupData);
Last but not least, there are better ways to iterate through a set in Java. Read about Iterators. It's a much secure and cleaner way to go through an array or a set.
It sounds to me like you've make a classic beginner mistake (for which you can be forgiven): not thinking enough in terms of objects.
Java's an object-oriented language. It sounds to me like your multiple lists of related items should really be a single List of objects that each contain their set of the items you're currently putting into multiple lists. Then you can sort that List of Objects using a Comparator any way you wish. All the related attributes are nicely encapsulated inside their object, where they belong. They stay together no matter how you sort them.
Objects are all about encapsulation and information hiding.
I finally figured it out! Thanks to a bigger project coming across a similar issue essentially forcing me to get this solved. Everything outside this sample is mostly the same as it was at the original post apart from some changed variable names. I'm not sure if this is the best way to do it, but it gets the job done at a very acceptable speed and I can actually understand how it works.
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
// Put separated item details in a HashMap for each item,
// then insert it in sorted order to list.
for(int n = 0; n < arrayTitle.size(); n++) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("title", arrayTitle.get(n));
item.put("desc", arrayDesc.get(n));
try {
int c, i = 0;
do {
// Compare new title with titles existing in list
// from beginning to end or until title is found that it goes before.
c = arrayTitle.get(n).compareTo(list.get(i).get("title"));
i++;
} while (c > 0 & i < list.size());
i--;
if(c > 0) {
// New item goes after all others currently in list.
list.add(item);
} else if (c < 0) {
// New item goes before an item already in list.
list.add(i, item);
}
} catch (Exception e) {
// If nothing in list to compare with, add first item.
list.add(item);
}
}
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, new String[] {"title", "desc"}, new int[]{android.R.id.text1, android.R.id.text2});
setListAdapter(adapter);
In Java, I have a Set, and I want to turn it into a sorted List. Is there a method in the java.util.Collections package that will do this for me?
The answer provided by the OP is not the best. It is inefficient, as it creates a new List and an unnecessary new array. Also, it raises "unchecked" warnings because of the type safety issues around generic arrays.
Instead, use something like this:
public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
List<T> list = new ArrayList<T>(c);
java.util.Collections.sort(list);
return list;
}
Here's a usage example:
Map<Integer, String> map = new HashMap<Integer, String>();
/* Add entries to the map. */
...
/* Now get a sorted list of the *values* in the map. */
Collection<String> unsorted = map.values();
List<String> sorted = Util.asSortedList(unsorted);
Sorted set:
return new TreeSet(setIWantSorted);
or:
return new ArrayList(new TreeSet(setIWantSorted));
Here's how you can do it with Java 8's Streams:
mySet.stream().sorted().collect(Collectors.toList());
or with a custom comparator:
mySet.stream().sorted(myComparator).collect(Collectors.toList());
List myList = new ArrayList(collection);
Collections.sort(myList);
… should do the trick however. Add flavour with Generics where applicable.
Always safe to use either Comparator or Comparable interface to provide sorting implementation (if the object is not a String or Wrapper classes for primitive data types) .
As an example for a comparator implementation to sort employees based on name
List<Employees> empList = new LinkedList<Employees>(EmpSet);
class EmployeeComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
}
Collections.sort(empList , new EmployeeComparator ());
Comparator is useful when you need to have different sorting algorithm on same object (Say emp name, emp salary, etc). Single mode sorting can be implemented by using Comparable interface in to the required object.
There's no single method to do that. Use this:
#SuppressWarnings("unchecked")
public static <T extends Comparable> List<T> asSortedList(Collection<T> collection) {
T[] array = collection.toArray(
(T[])new Comparable[collection.size()]);
Arrays.sort(array);
return Arrays.asList(array);
}
You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).
Here is the code:
keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);
Collections.sort(list);
TreeSet sortedset = new TreeSet();
sortedset.addAll(originalset);
list.addAll(sortedset);
where originalset = unsorted set and list = the list to be returned
#Jeremy Stein I wanted to implement same code. As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable.
This code helped me,
set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());
I am using this code, which I find more practical than the accepted answer above:
List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));