sorting using comparable java - java

I'm trying to sort an array of records. But I get "not a Record" error. The method getCt() is in a different class, the program compiles and the array is of the record type. I really don't know what is wrong with this code.
HashTable:
public class HashTable {
private Record [] array;
private int size;
private int indexSize=0;
private boolean updated,found;
public HashTable(int m){
array= new Record[m];
size=0;
}
public void getCt() {
Arrays.sort(array);
// return array[0];
}
Record class:
import java.lang.Comparable;
import java.util.*;
public class Record implements Comparable {
private Integer count;
private DNSkey key;
public Record(DNSkey key) {
this.key = key;
count = 1;
}
public void update() {
count++;
}
public DNSkey getKey() {
return key;
}
public Integer getCount() {
return count;
}
public int compareTo(Object obj) {
if (!(obj instanceof Record)) {
throw new ClassCastException("Not a Record");
}
Record check = (Record) obj;
return getCount().compareTo(check.getCount());
}
public String toString() {
return getKey() + " " + getCount();
}
}

one easy way is to use generics :
public class Record implements Comparable<Record> {
...
public int compareTo(Record check){
return getCount().compareTo(check.getCount());
}

My guess would be null items in the array. "null instanceof Class" will return false.
This will throw the Exception:
Record[] array = new Record[] { new Record(...), null };
Arrays.sort(array);

Use generics! And an #Override annotation.

Related

Using comparator with multiple comparators

I can use all the simple comparators in this code for sorting just fine but not the ComplexComparator. I couldn't figure it out how to code to get it to work properly. Any suggestion / explanation would be appreciated.
This is my main program:
package pkgTest;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Student[] students = new Student[6];
students[0] = new Student("Pete", 1989, 3.6);
students[1] = new Student("Tomas", 1989, 3.9);
students[2] = new Student("Helen", 1990, 3.6);
students[3] = new Student("Steve", 1991, 3.7);
students[4] = new Student("Natalie", 1993, 3.7);
students[5] = new Student("John", 1992, 4.0);
NameComparator byName
= new NameComparator();
BirthDateComparator byBirthDate
= new BirthDateComparator();
AverageComparator byAverage
= new AverageComparator();
ComplexComparator complexSorting
= new ComplexComparator(byName,
byAverage);
System.out.println("===============");
System.out.println("Before sorting:");
System.out.println("===============");
for (Student student : students) {
System.out.println(student.getName()
+ " // " + student.getBirthDate()
+ " // " + student.getAverage());
}
Arrays.sort(students, complexSorting);
System.out.println("==============");
System.out.println("After sorting:");
System.out.println("==============");
for (Student student : students) {
System.out.println(student.getName()
+ " // " + student.getBirthDate()
+ " // " + student.getAverage());
}
}
}
Here are the rest of the classes:
package pkgTest;
public class Student {
private String name;
private int birthDate;
private double average;
public Student(String name, int birthDate,
double average) {
this.name = name;
this.birthDate = birthDate;
this.average = average;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getBirthDate() {
return this.birthDate;
}
public void setBirthDate(int birthDate) {
this.birthDate = birthDate;
}
public double getAverage() {
return this.average;
}
public void setAverage(double average) {
this.average = average;
}
}
package pkgTest;
import java.util.Comparator;
public class ComplexComparator implements Comparator<Student> {
public ComplexComparator(Comparator<Student> one,
Comparator<Student> another) {
}
#Override
public int compare(Student one, Student another) {
/*This is the part that
I just couldn't figure
it out to get it work.
It has to work no matter
which 2 of the 3 comparators
I use to set the input
parameters of ComplexComparator.
I have to make it work by
modifying only this part of
the code.*/
}
}
package pkgTest;
import java.util.Comparator;
public class AverageComparator implements Comparator<Student> {
#Override
public int compare(Student one, Student another) {
if (one.getAverage()
< another.getAverage()) {
return -1;
} else if (one.getAverage()
== another.getAverage()) {
return 0;
} else {
return +1;
}
}
}
package pkgTest;
import java.util.Comparator;
public class BirthDateComparator implements Comparator<Student> {
#Override
public int compare(Student one, Student another) {
if (one.getBirthDate()
< another.getBirthDate()) {
return -1;
} else if (one.getBirthDate()
== another.getBirthDate()) {
return 0;
} else {
return +1;
}
}
}
package pkgTest;
import java.util.Comparator;
public class NameComparator implements Comparator<Student> {
#Override
public int compare(Student one, Student another) {
return one.getName().
compareToIgnoreCase(another.getName());
}
}
You will have to modify the class ComplexComparator like the following, at least...
import java.util.Comparator;
public class ComplexComparator implements Comparator<Student> {
private Comparator<Student> comparatorOne;
private Comparator<Student> comparatorTwo;
public ComplexComparator(Comparator<Student> one,
Comparator<Student> another) {
this.comparatorOne = one;
this.comparatorTwo = another;
}
#Override
public int compare(Student one, Student another) {
// make a first comparison using comparator one
int comparisonByOne = comparatorOne.compare(one, another);
// check if it was 0 (items equal in that attribute)
if (comparisonByOne == 0) {
// if yes, return the result of the next comparison
return comparatorTwo.compare(one, another);
} else {
// otherwise return the result of the first comparison
return comparisonByOne;
}
}
}
For more than two Comparators you will need a List of them (or another overloaded constructor) and a loop that keeps a certain order of comparisons.
EDIT
For your additional requirement regarding sorting orders, this may be helpful:
public class ComplexComparator implements Comparator<Student> {
private Comparator<Student> comparatorOne;
private Comparator<Student> comparatorTwo;
private boolean orderOneAscending = true;
private boolean orderTwoAscending = true;
/**
* Constructor without any sort orders
* #param one a comparator
* #param another another comparator
*/
public ComplexComparator(Comparator<Student> one, Comparator<Student> another) {
this.comparatorOne = one;
this.comparatorTwo = another;
}
/**
* Constructor that provides the possibility of setting sort orders
* #param one a comparator
* #param orderOneAscending sort order for comparator one
* (true = ascending, false = descending)
* #param another another comparator
* #param orderTwoAscending sort order for comparator two
* (true = ascending, false = descending)
*/
public ComplexComparator(Comparator<Student> one, boolean orderOneAscending,
Comparator<Student> another, boolean orderTwoAscending) {
this.comparatorOne = one;
this.comparatorTwo = another;
this.orderOneAscending = orderOneAscending;
this.orderTwoAscending = orderTwoAscending;
}
#Override
public int compare(Student one, Student another) {
int comparisonByOne;
int comparisonByAnother;
if (orderOneAscending) {
/* note that your lexicographical comparison in NameComparator
returns a negative integer if the String is greater!
If you take two numerical Comparators, the order will
turn into the opposite direction! */
comparisonByOne = comparatorOne.compare(another, one);
} else {
comparisonByOne = comparatorOne.compare(one, another);
}
if (orderTwoAscending) {
comparisonByAnother = comparatorTwo.compare(one, another);
} else {
comparisonByAnother = comparatorTwo.compare(another, one);
}
if (comparisonByOne == 0) {
return comparisonByAnother;
} else {
return comparisonByOne;
}
}
}
Just play around with the values and try some modifications to get familiar with common problems concerning comparing and sorting.
I hope this will be helpful...
Modify Your ComplexComparator as below
public class ComplexComparator implements Comparator<Student> {
private List<Comparator<Student>> listComparators;
#SafeVarargs
public ComplexComparator(Comparator<Student>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
#Override
public int compare(Student studen1, Student studen2) {
for (Comparator<Student> comparator : listComparators) {
int result = comparator.compare(studen1, studen2);
if (result != 0) {
return result;
}
}
return 0;
}
}
Here is a generic complex comparator you can use for any type of of objects (based on this answer):
public class ComplexComparator<T> implements Comparator<T> {
private List<Comparator<T>> listComparators;
#SafeVarargs
public ComplexComparator(Comparator<T>... comparators) {
listComparators = Arrays.asList(comparators);
}
#Override
public int compare(T o1, T o2) {
for (Comparator<T> comparator : listComparators) {
int result = comparator.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
}
There will be an unchecked cast warning when you use it, but you can suppress that, given that it will cast successfully as long as your class is comparable.
#SuppressWarnings("unchecked")
Comparator<MyClass> comparator = new ComplexComparator(
MyClass.ComparatorA,
MyClass.ComparatorB);
Collections.sort(mySet, comparator);
If anyone knows a way how to not get that warning, please comment and I update the answer.
I am not sure exactly how you want the solution to be presented. But from my understanding, if you want to do it by just putting code in the commented place, you can just try putting code like this.
Assuming the case when after comparing name, if same, you intend to move to average.
public int compare(Student StOne, Student StAnother) {
if(one.compare(Sone, Sanother)==0) {
return another.compare(StOne, StAnother);
}
else
return one.compare(StOne, StAnother);
}
But for this, you need to ensure that the values you take in the constructor of ComplexComparator (byName, byAverage) should be the instance variables of the class, and need to be initialized in the constructor.
public class ComplexComparator implements Comparator<Student> {
private Comparator<Student> one;
private Comparator<Student> another;
public ComplexComparator(Comparator<Student> one,
Comparator<Student> another) {
this.one=one;
this.another=another;
}
#Override
public int compare(Student one, Student another) {
//code given above
} }

Sort elements in list by enum value or string value

I want to sort an ArrayList in ascending order and in descending order by comparing a String value or an Enum value.
This is the ArrayList I want to sort :
List<Issue> issues;
The list will be sorted depending on two params (field and sort) I give to a function :
private List<Issue> sortList(List<Issue> list, String field, String sort) {
// My code goes here
}
So let's assume that the field value is title and the sort values is DESC then I want to order all Issue elements in the list by their title filed, this is what I tried :
return list.stream().sorted((i1, i2) -> String.compare(i2.getTitle(), i1.getTitle())).collect(Collectors.toList());
But this generates the following error :
The method compare(String, String) is undefined for the type String
For the enums I couldn't figure out how to compare their values.
How can I solve this ?
Classes definition :
Issue :
public class Issue {
private IssueElementEnum issueElement;
private IssueTypeEnum issueType;
private String title;
// Getters and setters
}
IssueElementEnum:
public enum IssueElementEnum {
PROFILE {
#Override
public String toString() {
return "Profil";
}
}
ROLE {
#Override
public String toString() {
return "Rôle";
}
},
User {
#Override
public String toString() {
return "Utilisateur";
}
}
}
IssueTypeEnum:
public enum IssueTypeEnum {
PROFILE {
#Override
public String toString() {
return "Sans Profil";
}
},
ROLE {
#Override
public String toString() {
return "Sans Rôle";
}
},
USER {
#Override
public String toString() {
return "Sans Utilisateur";
}
}
}
Edit :
Sometimes I want to sort my list with more than one field, for example (sort the list by title in ascending order and then by issueElement.toSting() in descending order, for that I created the following class :
public class SortDTO implements ISort {
public static final String ASC = "ASC";
public static final String DESC = "DESC";
private String field;
private String sort;
public GridSortDTO() {
this(null, null);
}
public GridSortDTO(final String field, final String sort) {
super();
this.field = field;
this.sort = sort;
}
#Override
public String getField() {
return field;
}
#Override
public void setField(final String field) {
this.field = field;
}
#Override
public String getSort() {
return sort;
}
#Override
public void setSort(final String type) {
this.sort = type;
}
#Override
public String toString() {
return String.format("Sort[field=%s, sort=%s]", this.field, this.sort);
}
}
public interface ISort {
String getField();
void setField(final String field);
String getSort();
void setSort(final String type);
}
Then my sort informations are stored in this array : GridSortDTO[] sorts.
So for example sorts will contain this information :
[{"field":"title","sort":"asc"},{"field":"issueElement","sort":"desc"}]
How can I implement this ?
It’s not clear which order you want for the enum types, declaration order (PROFILE, ROLE, USER) or lexicographic order of their toString() representation.
In the latter case, you could implement the method as
private List<Issue> sortList(List<Issue> list, String field, String sort) {
Function<Issue,String> f;
switch(field) {
case "Title": f = Issue::getTitle; break;
case "IssueElement": f = i -> i.getIssueElement().toString(); break;
case "IssueType": f = i -> i.getIssueType().toString(); break;
default: throw new IllegalArgumentException("unknown property '"+field+"'");
}
Comparator<Issue> cmp = Comparator.comparing(f);
if("DESC".equalsIgnoreCase(sort)) cmp = cmp.reversed();
else if(!"ASC".equalsIgnoreCase(sort))
throw new IllegalArgumentException("invalid sort '"+sort+"'");
return list.stream().sorted(cmp).collect(Collectors.toList());
}
If you want to use the enum declaration order instead, you have slightly less common code:
private List<Issue> sortList(List<Issue> list, String field, String sort) {
Comparator<Issue> cmp;
switch(field) {
case "Title": cmp = Comparator.comparing(Issue::getTitle); break;
case "IssueElement": cmp = Comparator.comparing(Issue::getIssueElement); break;
case "IssueType": cmp = Comparator.comparing(Issue::getIssueType); break;
default: throw new IllegalArgumentException("unknown property '"+field+"'");
}
if("DESC".equalsIgnoreCase(sort)) cmp = cmp.reversed();
else if(!"ASC".equalsIgnoreCase(sort))
throw new IllegalArgumentException("invalid sort '"+sort+"'");
return list.stream().sorted(cmp).collect(Collectors.toList());
}
Instead of the switch statement, you could also maintain a map of existing orders, which offers more flexibility:
// in Java 9, you should replace Arrays.asList(...) with List.of(...)
static final Map<List<String>,Comparator<Issue>> ORDER;
static {
Map<List<String>,Comparator<Issue>> m = new HashMap<>();
Comparator<Issue> c = Comparator.comparing(Issue::getTitle);
m.put(Arrays.asList("Title", "asc"), c);
m.put(Arrays.asList("Title", "desc"), c.reversed());
c = Comparator.comparing(Issue::getIssueElement);
m.put(Arrays.asList("IssueElement", "asc"), c);
m.put(Arrays.asList("IssueElement", "desc"), c.reversed());
c = Comparator.comparing(Issue::getIssueType);
m.put(Arrays.asList("IssueType", "asc"), c);
m.put(Arrays.asList("IssueType", "desc"), c.reversed());
ORDER = Collections.unmodifiableMap(m);
}
private List<Issue> sortList(List<Issue> list, String field, String sort) {
Comparator<Issue> cmp = ORDER.get(Arrays.asList(field, sort.toLowerCase(Locale.ROOT)));
if(cmp == null)
throw new IllegalArgumentException("property '"+field+"', sort '"+sort+"'");
return list.stream().sorted(cmp).collect(Collectors.toList());
}
This approach can be adapted to your new requirement, though, I strongly suggest a slight redesign:
enum Direction { ASCENDING, DESCENDING }
public interface ISort {
String getField();
void setField(final String field);
Direction getSort();
void setSort(final Direction type);
}
Adapting the implementation is straight-forward, but you should avoid allowing null for the sorting direction, as then, it’s intrisically only either of the two legal values:
public class SortDTO implements ISort {
private String field;
private Direction sort;
public SortDTO() { this(null, Direction.ASCENDING); }
public SortDTO(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
public String getField() { return field; }
public void setField(String field) { this.field = field; }
public Direction getSort() { return sort; }
public void setSort(Direction sort) { this.sort = Objects.requireNonNull(sort); }
#Override
public String toString() {
return String.format("Sort[field=%s, sort=%s]", this.field, this.sort);
}
}
We augment these types with an immutable key type capable of capturing the current state of an ISort implementation and having proper equals and hashCode implementations:
final class SortKey {
final String field;
final Direction direction;
private SortKey(String f, Direction d) { field=f; direction=d; }
#Override
public int hashCode() {
return field.hashCode()*2+direction.ordinal();
}
#Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(!(obj instanceof SortKey)) return false;
SortKey that = (SortKey)obj;
return this.direction == that.direction && this.field.equals(that.field);
}
static SortKey of(String field, Direction dir) {
return new SortKey(Objects.requireNonNull(field), Objects.requireNonNull(dir));
}
static SortKey of(ISort s) {
return of(s.getField(), s.getSort());
}
}
Then, the adapted solution may look like
static final Map<SortKey,Comparator<Issue>> ORDER;
static {
Map<SortKey,Comparator<Issue>> m = new HashMap<>();
Comparator<Issue> c = Comparator.comparing(Issue::getTitle);
m.put(SortKey.of("Title", Direction.ASCENDING), c);
m.put(SortKey.of("Title", Direction.DESCENDING), c.reversed());
c = Comparator.comparing(Issue::getIssueElement);
m.put(SortKey.of("IssueElement", Direction.ASCENDING), c);
m.put(SortKey.of("IssueElement", Direction.DESCENDING), c.reversed());
c = Comparator.comparing(Issue::getIssueType);
m.put(SortKey.of("IssueType", Direction.ASCENDING), c);
m.put(SortKey.of("IssueElement", Direction.DESCENDING), c.reversed());
ORDER = Collections.unmodifiableMap(m);
}
private List<Issue> sortList(List<Issue> list, ISort... order) {
if(order.length == 0) return new ArrayList<>(list);
Comparator<Issue> cmp = ORDER.get(SortKey.of(order[0]));
if(cmp == null) throw new IllegalArgumentException(order[0].toString());
for(int ix = 1; ix < order.length; ix++) {
Comparator<Issue> next = ORDER.get(SortKey.of(order[ix]));
if(next == null) throw new IllegalArgumentException(order[ix].toString());
cmp = cmp.thenComparing(next);
}
return list.stream().sorted(cmp).collect(Collectors.toList());
}
This allows an arbitrary number of sort criteria, the first being the primary order, the second being the secondary order and so on.
Actually, the method to compare two strings that you are trying to use is compareTo and not compare, which is defined in the Comparable interface. Take a look in the javadoc: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
If you want to sort your list by the title just use the following:
stream().sorted(Comparator.comparing(Issue::getTitle)).collect(Collectors.toList())
Please have a look at java-8 Comparator

Sort ArrayList via specific Value in ArrayList Object?

I have a Score System that I want to create, in which there is a list of players ranging their score from highest to lowest.
My PlayerObject.class Class:
public class PlayerObject {
private String playerName;
private int playerScore;
public int getScore() {
return this.playerScore;
}
public String getName() {
return this.playerName;
}
public void setNameAndScore(String givenName, int givenScore) {
this.playerName = givenName;
this.playerScore = givenScore;
}
}
My Array:
ArrayList<PlayerObject> allPlayers = new ArrayList<PlayerObject>();
Any idea how I can sort each player in the array list based on their playerScore attribute?
There are a lot of ways you can do it. First this is PlayerObject class:
public class PlayerObject implements Comparable<PlayerObject> {
private String playerName;
private int playerScore;
public PlayerObject(String playerName, int playerScore) {
this.playerName = playerName;
this.playerScore = playerScore;
}
public String getPlayerName() {
return playerName;
}
public int getPlayerScore() {
return playerScore;
}
#Override
public int compareTo(PlayerObject o) {
return Integer.compare(playerScore, o.playerScore);
}
}
And this is how you can sort it:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
List<PlayerObject> players = new ArrayList<>(2);
players.add(new PlayerObject("player1", 2));
players.add(new PlayerObject("player2", 4));
// if PlayerObject implements Comparable<PlayerObject>
Collections.sort(players);
// or if you want explicit Comparator
players.sort(new Comparator<PlayerObject>() {
#Override
public int compare(PlayerObject o1, PlayerObject o2) {
return Integer.compare(o1.getPlayerScore(), o2.getPlayerScore());
}
});
// or you can use lambda if you use Java 8
players.sort((o1, o2) -> Integer.compare(o1.getPlayerScore(), o2.getPlayerScore()));
// or even more concise
players.sort(Comparator.comparingInt(PlayerObject::getPlayerScore));
}
}
Here is a documentation that will help you:
Comparable
Comparator
One of the possible way to implement Comparable in your PlayerObject class and override compareTo method.
public class PlayerObject implements Comparable<PlayerObject> {
...
...
#Override
public int compareTo(PlayerObject o) {
// You can interchange the return value (-1 and 1) to change the sorting order
if(getPlayerScore() > o.getPlayerScore())
{
return -1
}
else if(getPlayerScore() < o.getPlayerScore())
{
return 1;
}
return 0;
}
}
With java 8, you can do it that way, without implementing any interface :
allPlayers = allPlayers.stream()
.sorted(Comparator.comparingInt(PlayerObject::getScore))
.collect(Collectors.toList());
Or just :
Collections.sort(allPlayers, Comparator.comparingInt(PlayerObject::getScore))
Consider using comparator.
Classic one
Collections.sort(allPlayers, new Comparator<PlayerObject>() {
#Override
public int compare(PlayerObject p1, PlayerObject p2) {
return p1.getScore().compareTo(p2.getScore());
}
});
And with java-8 Lambda support
allPlayers.sort(
(PlayerObject p1, PlayerObject p2) -> p1.getScore().compareTo(h2.getScore()));

Java Generic treeMap with comparator declaration without warning

There is any way i can do next with out getting the yellow warning / #SuppressWarnings("unchecked")
Generics objects :
P=product to compare,C = custoumer
public static myComparator<Product<P>> comparator= new myComparator<Product<P>>();
comparator declaration is outside "insertIntoMap" method,
i cant use the Product object inside "insertIntoMap" method .
public static <P,C> TreeMap<P, C> insertIntoMap(LinkedHashSet<P> set,C[] ac){
#SuppressWarnings("unchecked")
TreeMap<P,C> treeMap = new TreeMap<P,C>((Comparator<? super P>) comparator);
int itrIndex=0;
Iterator<P> itr = set.iterator();
while(itr.hasNext()){
treeMap.put(itr.next(), ac[itrIndex]);
itrIndex++;
}
return (TreeMap<P, C>) treeMap;
}
public static class myComparator<E> implements Comparator<Product<? super E>>{
#Override
public int compare(Product<? super E> o1, Product<? super E> o2) {
if(o1.getName().length()>o2.getName().length())
return 1;
else return -1;
}
}
Product Class :
public static class Product<E> implements Comparable<E>{
private E serialNum;
private String name;
Product(E serialNum,String name){
setSerialNum(serialNum);
setName(name);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
result = prime * result + ((serialNum == null) ? 0 : serialNum.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
Product<?> other = (Product<?>) obj;
if (serialNum.equals(other.serialNum))return true;
else return false;
}
public E getSerialNum() {
return serialNum;
}
public void setSerialNum(E serialNum) {
this.serialNum = serialNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return serialNum.toString()+": "+name;
}
#Override
public int compareTo(E o) {
if(this.hashCode()>o.hashCode())return 1;
else if(this.hashCode()<o.hashCode()) return -1;
else return -1;
}
}
Thanks !
From the code you posted it seems:
myComparator should not be generic:
public class myComperator implements Comparator<Product<?>> {
#Override
public int compare(Product<?> o1, Product<?> o2) {
if (o1.getName().length() > o2.getName().length())
return 1;
else if (o1.getName().length() < o2.getName().length())
return -1;
else
return -1;
}
}
insertIntoMap should only work for P extending Product. Otherwise you cannot use myComperator (which compares Products):
public static <P extends Product<?>, C> TreeMap<P, C> insertIntoMap(
LinkedHashSet<P> set, C[] ac) {
TreeMap<P, C> treeMap = new TreeMap<P, C>(new myComperator());
int itrIndex = 0;
Iterator<P> itr = set.iterator();
while (itr.hasNext()) {
treeMap.put(itr.next(), ac[itrIndex]);
itrIndex++;
}
return treeMap;
}

Sorting values with Comparator changes all the values with that object

I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);

Categories