简体   繁体   中英

Java collections not sorting complete string

I'm working on one task where I have to check the column data in Asc and Dec order and verify it. I'm using java collections for this.

What exactly my approach first im sorting the column in Asc order and pick all the column data and store in Array list. Its already in Asc order. After this im making another temp array list and sort it with help of java collections. After this Im comparing both list and its surely return true.

But java collections returns me different list after the sorting and its not equal when im working date filed.

//myList contains all the web elements
List<WebElement> myList=driver.findElements(By.xpath("//td[2]//span[@class='ui-cell-data']"));
List<String> all_elements_text=new ArrayList<>();
for(int i=0; i<myList.size(); i++) {
     //loading text of each element in to array all_elements_text
     all_elements_text.add(myList.get(i).getText());
}
//Just printing the array to verify the data manualy 
for(int y=0; y<all_elements_text.size(); y++) {
     System.out.println(all_elements_text.get(y));
}
//Sorting part
List tmp = new ArrayList(all_elements_text);
Collections.sort(tmp);
//Just printing the array to verify the data manualy 
for(int t=0; t<tmp.size(); t++) {
    System.out.println(tmp.get(t));
}
boolean sorted = tmp.equals(all_elements_text);
System.out.println("the boolean turns out to be: " + sorted);

here is sorting result before the collection

03 Oct 2018, 12:42
12 Nov 2018, 15:03
12 Nov 2018, 19:09
15 Nov 2018, 12:49
21 Nov 2018, 15:12
28 Nov 2018, 14:47
05 Dec 2018, 16:20
05 Dec 2018, 16:22
05 Dec 2018, 16:23
05 Dec 2018, 16:24

Here is after the collections

03 Oct 2018, 12:42
05 Dec 2018, 16:20
05 Dec 2018, 16:22
05 Dec 2018, 16:23
05 Dec 2018, 16:24
12 Nov 2018, 15:03
12 Nov 2018, 19:09
15 Nov 2018, 12:49
21 Nov 2018, 15:12
28 Nov 2018, 14:47

Please suggest something or any solution how it will work on date and even all the data formats basically

You are sorting text here, the java sort makes sense because doesn't know that you are using dates and not text.

If you need to sort threating the datas as dates you need to convert the ArrayList into an ArrayList.

You can convert each string in date in this way.

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("d MMM yyyy, HH:mm");

<date> = DATE_FORMAT.parse(<string value>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM