Sort alphanumeric string Java
•
Java
I have this array to store the suffixes of some URLs added by the user:
[U2,U3,U1,U5,U8,U4,U7,U6]
When I do this:
for (Map<String,String> map : getUrlAttachments()) { String tmpId = map.get("id"); //it receives the U2,in the 1st iteration,then U3,then U1,... if (tmpId.charAt(0) == 'U') { tmpId.charAt(1);//2,then 3,then 1,... String url = map.get("url"); String description = map.get("description"); URLAttachment attachment; String cleanup = map.get("cleanup"); if (cleanup == null && url != null && description != null) { attachment = new URLAttachmentImpl(); attachment.setOwnerClass(FileUploadOwnerClass.Event.toString()); attachment.setUrl(url); attachment.setDescription(description); attachment.setOwnerId(auctionHeaderID); attachment.setUrlAttachmentType(URLAttachmentTypeEnum.EVENT_ATTACHMENT); attachment.setDateAdded(new Date()); urlBPO.save(attachment); }
My question:
I want to change the for condition by passing another list, which maps data sorted like [U1, U2, U6, U8]
I hope your help will know the best way I can do it
I want to create an array of IDS and sort them, but I don't know how to sort alphanumeric strings in Java
Solution
I decided to use the idea given by @ Abu, but I adapted it:
>I check the ID of the URL that the user is trying to add, > I delete the letter suffix in this ID, and then create an ArrayList to store the numeric part of each ID. > I sort the ArrayList like @ Abu, teach me in his answer, and then I verify each ID in the sorted ArrayList in the order it should be added
ArrayList <Integer> urlSorted = new ArrayList<Integer>(); //sort the url ids for (Map<String,String> map : getUrlAttachments()) { String tmpId = map.get("id"); if (tmpId.charAt(0) == 'U') { //gets the id,removing the prefix 'U' urlSorted.add( Integer.valueOf(tmpId.substring(1))); } } //sort the urlIds to check the sequence they must be added Collections.sort(urlSorted); //checks for each url id,compares if it's on the natural order of sorting to be added. for(Integer urlId: urlSorted) { for (Map<String,String> map : getUrlAttachments()) { String sortedId = "U"+urlId; String tmpId = map.get("id"); //compare the ids to add the 1,then 2,then 3... if (map.get("id").equals(sortedId)) { //code to save according to the sorted ids. } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码