Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

Sorting alphanumeric strings java

I have this array storing the suffix of some URLs the user is adding:

[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 problem:

I want to change this For condition by passing another list mapping the data sorted like [U1, U2, U3, U4, U5, U6, U7, U8].

I'd like your help to know what's the best way I could do this.

I thought about creating an array listing the ids and then sort then, but I don't know how exactly to sort alphanumeric strings in java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just use Collections.sort() method after creating an ArrayList of your values like this:

ArrayList<String> a = new ArrayList<String>();
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);

Output :

Before : [U2, U1, U5, U4, U3]
After : [U1, U2, U3, U4, U5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...