Comparable Sort Numbers Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
This is my complete program
public class Client {
public static void main(String args[]) {
ArrayList < Student > studentsList = new ArrayList <> ();
Student std1 = new Student("Ram","01-01-1981","1203");
Student std2 = new Student("Raj","01-01-1981","1204");
Student std3 = new Student("Hanish","01-01-1981","403");
Student std4 = new Student("Hanish","01-01-1981","");
studentsList.add(std1);
studentsList.add(std2);
studentsList.add(std3);
studentsList.add(std4);
Collections.sort(studentsList);
System.out.println(studentsList);
}
}
When i print i see that the GL Number is not coming in acsending Order

The problem is that you are comparing the String GlNumber, not the number it represents. You state in the code that GLNumber is alphanumeric, so I think it's fair to say that your comparator works to spec.
"1204" < "403"
1204 > 403
On a side note: why store studentDOJ as String too? Seems like it should be java.time.LocalDate.

This happens because your glNumber is in String and You want numerical ascending.
You can understand the problem using the following examples
Sample 1
List stringList = Arrays.asList("1","2","10");
Collections.sort(stringList);
System.out.println(stringList);
// Returns [1, 10, 2]
Sample 2
List numberList = Arrays.asList(1,2,10);
Collections.sort(numberList);
System.out.println(numberList);
// Returns [1, 2, 10]
Now, the solution to your problem. Try below compareTo(...)
#Override
public int compareTo(Student other) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
return Comparator.comparing((Student student) -> LocalDate.parse(student.getStudentDOJ(), formatter)).reversed()
.thenComparingLong(student -> student.getGlNumber().length() == 0 ? 0 : Long.valueOf(student.getGlNumber()))
.compare(this, other);
}

create studentDateComparator which implements Comparator as follows:
#Override
public int compare(Student a, Student b) {
// ascending
// int r = a.getStudentDOJ().compareTo(b.getStudentDOJ());
// decending
int r = b.getStudentDOJ().compareTo(a.getStudentDOJ());
if (r == 0) {
r = comparison(a, b);
}
return r;
}
public int comparison(Student a, Student b) {
String s1 = a.getGlNumber();
String s2 = b.getGlNumber();
String[] pt1 = s1.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))");
String[] pt2 = s2.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))");
// pt1 and pt2 arrays will have the string split in alphabets and numbers
int i = 0;
if (Arrays.equals(pt1, pt2))
return 0;
else {
for (i = 0; i < Math.min(pt1.length, pt2.length); i++)
if (!pt1[i].equals(pt2[i])) {
if (!isNumber(pt1[i], pt2[i])) {
if (pt1[i].compareTo(pt2[i]) > 0)
return 1;
else
return -1;
} else {
int nu1 = Integer.parseInt(pt1[i]);
int nu2 = Integer.parseInt(pt2[i]);
if (nu1 > nu2)
return 1;
else
return -1;
}
}
}
if (pt1.length > i)
return 1;
else
return -1;
}
private static Boolean isNumber(String n1, String n2) {
// TODO Auto-generated method stub
try {
int nu1 = Integer.parseInt(n1);
int nu2 = Integer.parseInt(n2);
return true;
} catch (Exception x) {
return false;
}
}
}
Here is your given class:
private String studentName;
private String studentDOJ;
private String GlNumber; // alphanumeric
public Student(String studentName, String date, String glNumber) {
super();
this.studentName = studentName;
this.studentDOJ = date;
GlNumber = glNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentDOJ() {
return studentDOJ;
}
public void setStudentDOJ(String studentDOJ) {
this.studentDOJ = studentDOJ;
}
public String getGlNumber() {
return GlNumber;
}
public void setGlNumber(String glNumber) {
GlNumber = glNumber;
}
#Override
public String toString() {
return "Student [studentName=" + studentName + ", studentDOJ=" + studentDOJ + ", GlNumber="
+ GlNumber + "]";
}
#Override
public int compareTo(Student arg0) {
return 0;
}
}
And your the main method will be like:
public static void main(String args[]) throws ParseException {
ArrayList<Student> studentsList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Student std1 = new Student("Ram", "01-01-1981", "1203");
Student std2 = new Student("Raj", "01-01-1981", "1204");
Student std3 = new Student("Hanish", "01-01-1981", "403");
Student std4 = new Student("Hanish", "01-01-1981", "");
studentsList.add(std1);
studentsList.add(std2);
studentsList.add(std3);
studentsList.add(std4);
System.out.println(studentsList);
Collections.sort(studentsList, new studentDateComparator());
System.out.println(studentsList);
}
}

Use This to get your desired solution.
int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
#Override
public int compareTo(Student other) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
return Comparator.comparing((Student student) -> LocalDate.parse(student.getStudentDOJ(), formatter)).reversed()
.thenComparing(student -> extractInt(student.getGlNumber()))
.compare(this, other);
}

Related

sort by date java basic list

I have a list in java that contains lines of string id;city;date;days;price;vehicle. I need to sort all of it by date.(it's from a csv file that I read)
My list:
List <Ticket> list = new LinkedList<Ticket>();
And the way it is defined:
class Ticket {
int id;
String city;
String date;
int days;
float price;
String vehicle;
Ticket(int i, String c, String y, int d, float p, String v) {
id = i;
city = c;
date = y;
days = d;
price = p;
vehicle = v;
}
I was trying bubble sort but I have no clue how to compare dates and all the examples I found had ArrayList or were comparing small amounts of dates. I'm sorry if this is a bad question I just don't know how to apply everything I found to my situation.
You can do this with Comparator interface. I prefer to convert the string into date first.
For dd/MM/yyyy (01/01/1970) pattern example (without conversion):
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list, new Comparator<Ticket>() {
public int compare(Ticket t1, Ticket t2) {
String[] dateParts1 = t1.date.split("/");
String[] dateParts2 = t2.date.split("/");
int yearResult = dateParts1[2].compareTo(dateParts2[2]);
if (yearResult != 0) {
return yearResult;
}
int monthResult = dateParts1[1].compareTo(dateParts2[1]);
if (monthResult != 0) {
return monthResult;
}
int dayResult = dateParts1[0].compareTo(dateParts2[0]);
if (dayResult != 0) {
return dayResult;
}
return 0;
}
});
or (with conversion):
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list2, new Comparator<Ticket>() {
public int compare(Ticket t1, Ticket t2) {
String pattern = "dd/MM/yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
try {
Date date1 = simpleDateFormat.parse(t1.date);
Date date2 = simpleDateFormat.parse(t2.date);
return date1.compareTo(date2);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
});
Also, you can do same thing in class with Comparable interface.
public class Ticket **implements Comparable<Ticket>** {
int id;
String city;
String date;
int days;
float price;
String vehicle;
Ticket(int i, String c, String y, int d, float p, String v) {
id = i;
city = c;
date = y;
days = d;
price = p;
vehicle = v;
}
**#Override
public int compareTo(Ticket o) {
String[] dateParts1 = this.date.split("/");
String[] dateParts2 = o.date.split("/");
int yearResult = dateParts1[2].compareTo(dateParts2[2]);
if (yearResult != 0) {
return yearResult;
}
int monthResult = dateParts1[1].compareTo(dateParts2[1]);
if (monthResult != 0) {
return monthResult;
}
int dayResult = dateParts1[0].compareTo(dateParts2[0]);
if (dayResult != 0) {
return dayResult;
}
return 0;
}**
}
Then:
List<Ticket> list = new LinkedList<Ticket>();
... //fill the list.
Collections.sort(list);
You can parse the date String to a date object like LocalDateTime or Instant and etc' (depending on your use case).
I randomly picked LocalDateTime for this example.
Then you can do:
tickets.add(new Ticket(1, "dsa", LocalDateTime.now().plusSeconds(5), 6, 5, "rew"));
tickets.add(new Ticket(0, "dsa", LocalDateTime.now(), 6, 5, "rew"));
List<Ticket> sortedTicketsByDate = tickets.stream()
.sorted(Comparator.comparing(t -> t.date)) // comparing by date
.collect(Collectors.toList());
System.out.println(sortedTicketsByDate);
Output:
[
Ticket(id=0, city=dsa, date=2021-05-02T23:46:03.214, days=6, price=5.0, vehicle=rew),
Ticket(id=1, city=dsa, date=2021-05-02T23:46:08.197, days=6, price=5.0, vehicle=rew)
]
Here is another clean version using java records (new since JDK 16) which is recommended for plain java objects (pojos) that store data.
Read more info in this article : https://www.baeldung.com/java-record-keyword
You implement the Comparable interface based on date and Collections.Sort() can sort your ArrayList based on that.
import java.util.ArrayList;
import java.util.Collections;
record Ticket(int id,String city,String date,int days,float price,String vehicle) implements Comparable<Ticket>{
public int compareTo(Ticket ticket){
return this.date.compareTo(ticket.date);
}
}
public class Main{
public static void main(String[] args) {
Ticket ticket1 = new Ticket(1,"New York","2021-05-03",10,110.30f,"Ferrari");
Ticket ticket2 = new Ticket(2,"Miami","2021-05-02",9,120.50f,"Porche");
Ticket ticket3 = new Ticket(3,"Los Angeles","2021-05-01",10,150.50f,"Mercedes");
var list = new ArrayList<Ticket>();
list.add(ticket1);
list.add(ticket2);
list.add(ticket3);
System.out.println("The List before sorting:\n");
list.forEach(System.out::println);
Collections.sort(list);
System.out.println("\nThe List After sorting:\n");
list.forEach(System.out::println);
}
}

How to return the Objects of an ArrayList on separate lines

I have created a program that sorts trading cards and places them in a collection that is then compared to other collections to look for duplicates. I have had no problems up until my final toString method. My issue is that I cannot seem to get the return statement to separate the various cards onto their own separate lines.
instead of Alan Turing, Grace Hopper, Ada Lovelace, I need:
Alan Turing
Grace Hopper
Ada Lovelace
Below is a copy of my code. I am fairly new to java so I apologize for any lack of knowledge pertaining to methods specific to this, but I have only found ones using System.out.println, and not mentioning return in any way. My problem lies in the method defined by **. I appreciate any and all help and am sorry if this question is not 100% clear. (I have tried my own research to no avail!)
// First Class
public class Card implements Comparable<Card> {
private String name;
private String nationality;
private int yearBorn;
private int yearDied;
public Card(String name, String nationality, int yearBorn, int yearDied) {
this.name=name;
this.nationality=nationality;
this.yearBorn=yearBorn;
this.yearDied=yearDied;
}
public int compareTo(Card c) {
if (this.name.equals(c.name)) return 0;
else if (this.name.compareTo(c.name)>0) return 1;
else return -1;
}
public String toString() {
return String.format("%s (%d - %d) - %s", name, yearBorn, yearDied, nationality);
}
}
// Second Class
import java.util.ArrayList;
import java.util.List;
public class CardCollection {
private String owner;
private List<Card> myCollection;
public CardCollection(String owner) {
this.owner = owner;
this.myCollection = new ArrayList<>();
}
public boolean addCard(Card c) {
int p = 0;
while (p < myCollection.size()) {
int q = myCollection.get(p).compareTo(c);
if (q == 0) {
return false;
} else if (q > 0) {
myCollection.add(p, c);
return true;
}
p++;
}
myCollection.add(c);
return true;
}
public void removeCard(int r) {
myCollection.remove(r);
}
public int getSize() {
return myCollection.size();
}
public ArrayList<Card> mergeCollections(CardCollection cc) {
ArrayList<Card> dupes = new ArrayList<>();
while (cc.getSize() > 0) {
Card c = cc.myCollection.remove(0);
if (myCollection.contains(c)) {
dupes.add(c);
}
else myCollection.add(c);
}
return dupes;
}
**public String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
return String.format("%s\n%s\n%s\n", owner, s, myCollection);**
}
}
// Runner Class
import java.util.ArrayList;
public class CCRunner {
public static void main(String[] args) {
CardCollection c1 = new CardCollection("Alan");
CardCollection c2 = new CardCollection("Grace");
Card turing = new Card("Alan Turing","British",1912,1954);
Card hopper = new Card("Grace Hopper","American",1906,1992);
Card vonneumann = new Card("John Von Neumann","Hungarian",1903,1957);
Card shannon = new Card("Claude Shannon","American",1916,2001);
Card johnson = new Card("Katherine Johnson","American",1918,-1);
Card lovelace = new Card("Ada Lovelace","British",1815,1852);
Card cerf = new Card("Vint Cerf","American",1943,-1);
Card brin = new Card("Sergey Brin","Russian",1973,-1);
c1.addCard(turing);
c1.addCard(vonneumann);
c1.addCard(shannon);
c1.addCard(johnson);
c1.addCard(cerf);
c1.addCard(brin);
c2.addCard(cerf);
c2.addCard(lovelace);
c2.addCard(johnson);
c2.addCard(vonneumann);
c2.addCard(hopper);
System.out.println(c1);
System.out.println(c2);
ArrayList<Card> dupes = c1.mergeCollections(c2);
System.out.println(c1);
System.out.println(c2);
System.out.println("Duplicates:\n-----------");
for (Card c : dupes) {
System.out.println(c);
}
}
}
This is run in a separate class, but I don't think it will elucidate my problem to include it. Let me know if I am wrong.
You can either change your implementation of toString() of your CardCollection class. Examples:
Loop again, this time over the List:
public final String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
for (int i = 0; i < myCollection.size(); i++) {
s += "\n" + myCollection.get(i);
}
return String.format("%s\n%s\n", owner, s);
}
Using a stream (requires an additional import java.util.stream.Collectors;):
public final String toString() {
String s = "";
for (int i = 0; i < owner.length(); i++) {
s += "-";
}
return String.format("%s\n%s\n%s\n",
owner,
s,
myCollection.stream()
.map(Card::toString)
.collect(Collectors.joining("\n")));
}
Or you can #Override the toString() method of the ArrayList, also in your CardCollection class. Example:
this.myCollection = new ArrayList<>(){
#Override
public String toString(){
String s = "";
if (size() > 0) s = get(0).toString();
for (int i = 1; i < size(); i++) {
s += "\n" + get(i).toString();
}
return s;
}
};
All examples will result in this for Alan (before the merge):
Alan
----
Alan Turing (1912 - 1954) - British
Claude Shannon (1916 - 2001) - American
John Von Neumann (1903 - 1957) - Hungarian
Katherine Johnson (1918 - -1) - American
Sergey Brin (1973 - -1) - Russian
Vint Cerf (1943 - -1) - American
Note: I'd personally go with changing the implementation of toString() of the CardCollection class. I would also perfer the way tquadrat did it in their answer. The overriding of ArrayList looks to messy in my opinion, and keeping the stringrepresentation in the toString() method makes more sense to me.
Try this as a replacement to the marked toString() implementation:
…
public final String toString()
{
var s = "-".repeat( owner.length() );
var joiner = new StringJoiner( "\n", String.format( "%s%n%s%n", owner, s ), "" );
for( var c : myCollection ) joiner.add( c.toString() );
var retValue = joiner.toString();
return retValue;
}
Basically, the output would look like this:
<owner>
-------
<collectible1>
<collectible2>
<…>
If you are using a Java version before Java 11, you may need to replace var with the respective types.

How to organise alphabetically an array of objects in Java

I am trying to simulate a library of Albums. But I would also be able to organise the contents of the library alphabetically by the author's name. Any help in how to organise the contents of the array of objects alphabetically?
I have created a Class called Album, which I use to create my objects
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
}
The class Collection is used to store the objects into an array
public class AlbumCollection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < collection.length ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
}
This is the class that I am using to create the Album Objects
public class TestCollection {
public static void main(String[] args) {
AlbumCollection c = new AlbumCollection();
c.add( new Album("DaftPunk","Discovery","2001"));
c.add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.add( new Album( "The Clash", "London Calling", "1979"));
System.out.print(c);
}
}
I had to change the compareTo method to sort by the author.
public class Album {
private String author;
private String name;
private String year;
public Album(String a, String n, String y) { // constructor
author = a;
name = n;
year = y;
}
public String toString()
{
return author +","+ name + "," + year;
}
public int compareTo(Album a) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return author.compareTo(a.author);
}
}
And i added method sort to sorting elements of array:
public class Collection {
public Album collection[]= new Album[10];
private int numAlbums = 0;
public void Add (Album a){
if (numAlbums >= collection.length){
Album newcollection[]= new Album [collection.length * 2];
for (int n = 0; n < numAlbums; n ++){
newcollection[n] = collection[n];
}
newcollection = collection;
}
collection[numAlbums] = a;
numAlbums = numAlbums + 1;
}
public String toString()
{
String details = "";
for ( int p = 0; p < numAlbums ; p ++)
{
details = details + collection[p] + "\n" ;
}
details += "\n";
return details;
}
public void sort(){
for(int i=0;i<numAlbums;i++){
for(int j=i;j<numAlbums-1;j++){
if(collection[j].compareTo(collection[j+1])>0){
Album tmp =collection[j];
collection[j]=collection[j+1];
collection[j+1]=tmp;
}
}
}
}
}
You can not use the length of an array, if you store the number of authors, because you will print null values
public static void main(String[] args) {
Collection c = new Collection();
c.Add( new Album("DaftPunk","Discovery","2001"));
c.Add( new Album ("Pink Floid","The Dark Side Of The Moon","1973"));
c.Add( new Album( "The Clash", "London Calling", "1979"));
c.sort();
System.out.print(c);
}

Sorting Duplicate Keys with respective values in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to sort house numbers in my project. But I did not get exact logic for my problem.
The list is:
9-11, 9-01, 10-02, 10-01, 2-09, 3-88, 9-03
I need to sort the above list as:
2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02
I need the output like above.
Can any one help me in Java coding?
The logic is simple here:
209 < 388 < 901 < 902 < 911 < 1001 < 1002
One possible solution is:
String[] input = {"9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03"};
Map<Integer, String> map = new TreeMap<Integer, String>();
for (String s : input) {
map.put(Integer.valueOf(s.replace("-", "")), s);
}
TreeSet<Integer> set = new TreeSet<Integer>(map.keySet());
String[] output = new String[input.length];
int i = 0;
for (Integer key : set) {
output[i++] = map.get(key);
}
If you want to support more flexible formats, you can implement Comparable to define exactly comparisson rules. Let's take a look at modified example:
class HouseNumber implements Comparable<HouseNumber>{
private Integer house;
private Integer flat;
private HouseNumber(String s) {
String[] fields = s.split("-");
house = Integer.valueOf(fields[0]);
flat = Integer.valueOf(fields[1]);
}
#Override
public int compareTo(HouseNumber o) {
if (house.compareTo(o.house) == 0) {
return flat.compareTo(o.flat);
}
return house.compareTo(o.house);
}
}
String[] input = {"9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03"};
Map<HouseNumber, String> map = new TreeMap<HouseNumber, String>();
for (String s : input) {
map.put(new HouseNumber(s), s);
}
TreeSet<HouseNumber> set = new TreeSet<HouseNumber>(map.keySet());
String[] output = new String[input.length];
int i = 0;
for (HouseNumber key : set) {
output[i++] = map.get(key);
}
Simply remove "-" from the list
9-11, 9-01, 10-02, 10-01, 2-09, 3-88, 9-03
becomes
911, 901, 1002, 1001, 209, 388, 903
Sort
209, 388, 901, 903, 911, 1001, 1002
Place the "-" back, skipping 2 places from the back
2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02
Simple as that !
Do like this
Your Comparator
class SimpleComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
String [] o1sub = o1.split("-");
String [] o2sub = o2.split("-");
int value1 = Integer.parseInt(o1sub[0]);
int value2 = Integer.parseInt(o2sub[0]);
if(value1!=value2){
return new Integer (value1).compareTo(value2);
}
int value3 = Integer.parseInt(o1sub[1]);
int value4 = Integer.parseInt(o2sub[1]);
if(value3!=value4){
return new Integer(value3).compareTo(value4);
}
return 0;
}
}
Data
String [] array ={"9-11","9-01","10-02","10-01","2-09","3-88","9-03"};
Sorting
Arrays.sort(array,new SimpleComparator());
System.out.println(Arrays.toString(array));
OutPut
[2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02]
I have share you solved problem, May be it will help you to get exactly you want...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class HouseNo {
public HouseNo(String house, String block) {
this.houseno = house;
this.blockno = block;
}
private String houseno;
private String blockno;
public String getHouseno() {
return houseno;
}
public void setHouseno(String houseno) {
this.houseno = houseno;
}
public String getBlockno() {
return blockno;
}
public void setBlockno(String blockno) {
this.blockno = blockno;
}
public static class SortByHouseNo implements Comparator<HouseNo> {
#Override
public int compare(HouseNo o1, HouseNo o2) {
Integer first = Integer.valueOf(o1.getHouseno());
Integer second = Integer.valueOf(o2.getHouseno());
Integer f1 = Integer.valueOf(o1.getBlockno());
Integer f2 = Integer.valueOf(o2.getBlockno());
if (first.compareTo(second) == 0) {
return f1.compareTo(f2);
}
return first.compareTo(second);
}
}
#Override
public String toString() {
return "House -> " + this.getHouseno() + "-" + this.getBlockno();
}
public static void main(String[] args) {
// Final
String houseList[] = { "9-11", "9-01", "10-02", "10-01", "2-09",
"3-88", "9-03", "9-3" };
HouseNo house = null;
ArrayList<HouseNo> sortedList = new ArrayList<>();
for (String string : houseList) {
String h = string.substring(0, string.indexOf('-'));
String b = string.substring(string.indexOf('-') + 1);
house = new HouseNo(h, b);
sortedList.add(house);
}
System.out.println("Before Sorting :: ");
for (HouseNo houseNo : sortedList) {
System.out.println(houseNo);
}
Collections.sort(sortedList, new SortByHouseNo());
System.out.println("\n\nAfter Sorting HouseNo :: ");
for (HouseNo houseNo : sortedList) {
System.out.println(houseNo);
}
}
}
Updated solution......

Sort dates in Java

I want to list dates from the most current date to the oldest date.
I don't want to use Collections.sort()so I made my own method.
When I do this :
List<Livre> maBibliotheque = new ArrayList<Livre>();
boolean tri = false;
int born = maBibliotheque.size();
while (tri == false)
{
tri = true ;
for (int i=0; i<born-1;i++)
{
if ( maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i+1).getNewPeriode())>0){
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i+1));
maBibliotheque.set(i+1,livre);
tri = false ; }
}
born -= born;
}
It works perfectly, but from the oldest to the newest date, but I want the otherwise.
I change this line to
if ( maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i+1).getNewPeriode())<0){
But it's doesn't make anything, no sort dates in this case. Please help
To reverse the order, replace > 0 with < 0
Doesn't
born -= born;
do the same as
born = 0;
I suspect this isn't needed.
This
public static void main(String[] args) throws IOException, IllegalAccessException, NoSuchFieldException {
List<Livre> maBibliotheque = new ArrayList<Livre>();
maBibliotheque.add(new Livre("aaa"));
maBibliotheque.add(new Livre("abb"));
maBibliotheque.add(new Livre("bbb"));
maBibliotheque.add(new Livre("000"));
boolean tri;
int born = maBibliotheque.size();
do {
tri = true;
for (int i = 0; i < born - 1; i++) {
if (maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i + 1).getNewPeriode()) > 0) {
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i + 1));
maBibliotheque.set(i + 1, livre);
tri = false;
}
}
} while (!tri);
System.out.println("increasing: " + maBibliotheque);
do {
tri = true;
for (int i = 0; i < born - 1; i++) {
if (maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i + 1).getNewPeriode()) < 0) {
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i + 1));
maBibliotheque.set(i + 1, livre);
tri = false;
}
}
} while (!tri);
System.out.println("decreasing: " + maBibliotheque);
}
static class Livre {
private final String newPeriode;
Livre(String newPeriode) {
this.newPeriode = newPeriode;
}
public String getNewPeriode() {
return newPeriode;
}
#Override
public String toString() {
return "Livre{" +
"newPeriode='" + newPeriode + '\'' +
'}';
}
}
prints
increasing: [Livre{newPeriode='000'}, Livre{newPeriode='aaa'}, Livre{newPeriode='abb'}, Livre{newPeriode='bbb'}]
decreasing: [Livre{newPeriode='bbb'}, Livre{newPeriode='abb'}, Livre{newPeriode='aaa'}, Livre{newPeriode='000'}]
Sort from oldest to newest, then reverse it with Collections.reverse(maBibliotheque);
I would recommend implementing a Comparator. You set a field in the Comparator object that can tell it whether to sort Ascending or Descending, then call Collections.sort(maBibliotheque, new MyComparator(MyComparator.DESC))
Demo (adjust generics as needed, and if, as in this case, you know that you're comparing with a specific field use o1.getField().compareTo(o2.getField()). Alternately, you could implement Comparable in your Object and just call Collections.sort(List), but that's not as flexible.
public class MyComparator implements Comparator<String>
{
public static final int ASC = 0;
public static final int DESC = 1;
private final int sortOrder;
public MyComparator(int sortOrder)
{
this.sortOrder = sortOrder;
}
/* (non-Javadoc)
* #see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
#Override
public int compare(String o1, String o2)
{
switch(this.sortOrder)
{
case ASC:
return o1.compareTo(o2);
case DESC:
return o2.compareTo(o1);
}
return 0;
}
}

Categories

Resources