Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Collections Use [closed]

I'm doing a small project and was wondering what might be the best (most efficient) way of ordering a bunch of Strings by:

  1. their length
  2. alphabetically

The former being the way to sort initially.

I was thinking of using a priority queue but I am unsure of whether there may be a more efficient way to sort the Strings.

Additionally, I am having difficulty in figuring out how to sort alphabetically after sorting by length. If anyone has a better way to sort these or knows how to sort after sorting the first time, an answer would be great.

like image 799
Sythe Avatar asked Apr 10 '26 04:04

Sythe


1 Answers

The most efficient comparison sorting implementation you can hope for will run in O(nlogn) time. There are many algorithms to choose from. Java has this functionality built-in.

To sort your strings by length, and then alphabetically, you should implement your own string comparison method using Comparator<String>

Comparator<String> comparator = new Comparator<String>(){

    @Override
    public int compare(String s1, String s2) {
        //TODO define the comparison based on length, and then alphabetically
        return 0;
    }
};
List<String> strings = ...
Collections.sort(strings, comparator);
like image 64
James Wierzba Avatar answered Apr 12 '26 16:04

James Wierzba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!