排序字母数字字符串java
我有这个数组存储用户添加的一些URL的后缀:
[U2, U3, U1, U5, U8, U4, U7, U6]
我这样做的时候:
for (Map 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); }
我的问题:
我想通过传递另一个列表来更改这个For
条件,这些列表映射了像[U1, U2, U3, U4, U5, U6, U7, U8]
这样排序的数据。
我希望你的帮助知道我能做到这一点的最佳方式。
我想创建一个列出id的数组然后排序,但我不知道如何在java中对字母数字字符串进行排序。
我决定使用@Abu给出的想法,但我改编了它:
- 我检查用户试图添加的url的ID,
- 我删除此id中的字母后缀,然后创建一个
ArrayList
来存储每个id的数字部分。 -
我将这个
ArrayList
排序为像@Abu一样在他的答案中教我,然后我按照它应该添加的顺序validation这个排序的ArrayList
中的每个id。ArrayList
urlSorted = new ArrayList (); //sort the url ids for (Map 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 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. } } }
在创建值的ArrayList
之后,只需使用Collections.sort()
方法,如下所示:
ArrayList a = new ArrayList (); a.add("U2"); a.add("U1"); a.add("U5"); a.add("U4"); a.add("U3"); System.out.println("Before : "+a); Collections.sort(a); System.out.println("After : "+a);
输出:
Before : [U2, U1, U5, U4, U3] After : [U1, U2, U3, U4, U5]
创建自定义Comparator
:
public class IdComparator implements Comparator
然后使用Arrays.sort(urlAttachments, new IdComparator());
在迭代它之前。 根据细节,您可以将此排序逻辑推送到getUrlAttachments()
并保持您已经发布的代码与现在完全相同。
我想你所问的与这个类似:
http://www.davekoelle.com/alphanum.html
您可以将字符串分解为纯字符串和数字字符串。 例如:abc123将分为“abc”和“123”您可以将字母字符串与正常比较进行比较,然后对“123”这类字符串进行排序,您有两种选择:1:将其转换为整数然后比较2 :如果数字不适合整数范围,您可以逐字母进行比较。
例如“123”vs“133”比较“1”和“1”=等于比较“2”和“3”=大于“123”<“133”。
选项2更准确,更少错误certificate。