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
425 views
in Technique[技术] by (71.8m points)

java - Sort ArrayList of strings by length

I want to order an ArrayList of strings by length, but not just in numeric order.

Say for example, the list contains these words:

cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical

They need to be ordered by their difference in length to a special string, for example:

intelligent

So the final list would look like this (difference in brackets):

aeronomical     (0)
telescopic      (1)
fantasmagorical (3) - give priority to positive differences? doesn't really matter
cucumber        (3)
bacon           (6)
tea             (8)
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use a custom comparator:

public class MyComparator implements java.util.Comparator<String> {

    private int referenceLength;

    public MyComparator(String reference) {
        super();
        this.referenceLength = reference.length();
    }

    public int compare(String s1, String s2) {
        int dist1 = Math.abs(s1.length() - referenceLength);
        int dist2 = Math.abs(s2.length() - referenceLength);

        return dist1 - dist2;
    }
}

Then sort the list using java.util.Collections.sort(List, Comparator).


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

2.1m questions

2.1m answers

60 comments

56.9k users

...