-1

If i have an ArrayList of strings ["bb", "ab", "cf", "aa"] how can I sort alphabetically by the 1st or nth index and onward (if 1st index is the same character for other strings) ? Is there a method I can use to do so?

The list above, I would expect for index = 1

["aa", "bb", "ab", "cf"]

Another example would

["bab", "baa", "abbe", "cff"] would return

["baa", "bab", "abbe", "cff"]

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
Liondancer
  • 15,721
  • 51
  • 149
  • 255

2 Answers2

1

You can use Comparator.comparingInt to perform this sort:

Using index 0 to sort arrays:

String[] s = {"bb", "ab", "cf", "aa"};
Arrays.sort(s, Comparator.comparingInt(s1 -> s1.charAt(0)));
Arrays.asList(s).forEach(System.out::println);

or sort lists:

List<String> s = Arrays.asList("bb", "ab", "cf", "aa");
s.sort(Comparator.comparingInt(s2 -> s2.charAt(0)));
s.forEach(System.out::println);

Outputs:

ab
aa
bb
cf

Otherwise using index 1 for sort arrays:

String[] s = {"bb", "ab", "cf", "aa"};
Arrays.sort(s, Comparator.comparingInt(s2 -> s2.charAt(1)));
Arrays.asList(s).forEach(System.out::println);

or index 1 for sorting lists

List<String> s = Arrays.asList("bb", "ab", "cf", "aa");  
s.sort(Comparator.comparingInt(s2 -> s2.charAt(1)));
s.forEach(System.out::println);

Outputs:

aa
bb
ab
cf

PS: You question about java, but your strings and array like javascript..

Stranger in the Q
  • 3,668
  • 2
  • 21
  • 26
0

Take a look at this simple example:

 public static void main(String[] args) {
        List<String> listOfStrings = new LinkedList<>();
        listOfStrings.add("aa");
        listOfStrings.add("bb");
        listOfStrings.add("ge");
        listOfStrings.add("be");
        System.out.println(Arrays.asList(listOfStrings));
        String getMe = listOfStrings.remove(3);
        listOfStrings.add(0, getMe);
        System.out.println(Arrays.asList(listOfStrings));
    }

LinkedList are good for insterting and removing elements and this can be done in O(1) (change it locally ), also I would like to mention that adding or removing a head of the list is done in O(1) too which is optimal for your cause.

MS90
  • 1,219
  • 1
  • 8
  • 17