Java program for alphanumeric sorting objects
Java program for alphanumeric sort objects
please let me know how i can get the expected result
Expected Result: Bi 2 D1 D2 D14 E2
Actual output: Bi 2 D1 D14 D2 E2
====================================
List<Name> lst = new ArrayList<>();
lst.add(new Name("D",1));
lst.add(new Name("D",14));
lst.add(new Name("D",2));
lst.add(new Name("E",2));
lst.add(new Name("B",2));
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// TODO Auto-generated method stub
String o1=n1.getNm()+n1.getSeatnum();
String o2=n2.getNm()+n2.getSeatnum();
return o1.compareTo(o2);
}
});
for (Name name : lst) {
System.out.println(name.getNm()+name.getSeatnum());
}
=================================
public class Name {
private String nm;
private int seatnum;
public int getSeatnum() {
return seatnum;
}
public void setSeatnum(int seatnum) {
this.seatnum = seatnum;
}
public Name(String nm) {
super();
this.nm = nm;
}
public Name(String nm, int seatnum) {
super();
this.nm = nm;
this.seatnum = seatnum;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
}
source to share
Yes, it is possible, but your function compare
must first check the part String
for equality and then use a numeric comparison for the part of the number (currently both compare lexically ). So, you can use something like:
public int compare(Name n1, Name n2) {
int c = n1.getNm().compareTo(n2.getNm());
if (c != 0) {
return c;
}
return Integer.valueOf(n1.getSeatnum()).compareTo(n2.getSeatnum());
}
source to share
You can rewrite your comparator to work in 2 steps:
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// compare the name part
int nameCompare = n1.getName().compareTo(n2.getName());
if(nameCompare != 0)
return nameCompare;
// compare the number part
return n1.getSeatnum() - n2.getSeatnum();
}
});
If you want to know the values null
, you must add:
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// check for null Name
if(n1 == null && n2 == null)
return 0;
else if(n1 == null)
return -1;
else if(n2 == null)
return 1;
// check for null in nx.getName()
if(n1.getName() == null && n2.getName() == null)
return 0;
else if(n1.getName() == null)
return -1;
else if(n2.getName() == null)
return 1;
// compare the name part
int nameCompare = n1.getName().compareTo(n2.getName());
if(nameCompare != 0)
return nameCompare;
// compare the number part
return n1.getSeatnum() - n2.getSeatnum();
}
});
This approach would put the values ββat the top of the list null
. If you prefer to have them at the end of the list, just replace 1
and -1
.
If you also want case insensitivity, change the name comparison string to:
int nameCompare = n1.getName().toLowerCase().compareTo(n2.getName().toLowerCase());
source to share