2

I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:

  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  import java.util.Scanner;


public class SortingAnArrayOfStrings {




public static void main(String[] args) {


{
     //Ask the user for names to add to the array
     List<String> list=new ArrayList<String>();
     Scanner in=new Scanner(System.in);
     do {
         System.out.println(" The names on the list are "+list);
         System.out.println("Would you like to add another name to the list? (y/n)");

         if (in.next().startsWith("y")) {
             System.out.println("Enter:");
             list.add(in.next());
         }else{break;

        }
     } while (true);
    //display the names that have been added to the array
    System.out.println("The names on the list are "+list);

    //sort the array of names in alphabetical order
    String[] Arr=list.toArray(new String[list.size()]);
    String[] stringArray=new String[Arr.length];

     for(int i=0;i<Arr.length;i++)
     {
         for (int j = i+1; j < Arr.length; j++) {
             if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
                 String temp=Arr[j];
                 Arr[j]=Arr[i];
                 Arr[i]=temp;
             }
         }
         stringArray[i]=Arr[i];
     }

     //display the sorted list of names
     System.out.println("This is the list of names after sorting them in alphabetical order : ");

     for(String ss:stringArray){
         System.out.print(ss + " ");

     }
  }

}
}

6 Answers 6

4

You could try something like bellow using a custom java.util.Comparator:

String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // TODO: Argument validation (nullity, length)
        return s1.charAt(1) - s2.charAt(1);//comparision
    }  
});

for (String name : names) System.out.println(name);

output:

Dan
Bob
Kris
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That was very helpful, but is it possible to write the program without using Comparator?
@pikProgram - you can do it manual parsing using for loop but there is chance to make mistake and code looks something verbose and hard to read. So we should use java feature to take advantage of language.
2

You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :

list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
    String sb1 = s1.substring(1);
    String sb2 = s2.substring(1);
    return sb1.compareTo(sb2);
    });

System.out.println("list = " + list);

The Result:

list = [Dan, Bob, Kris]

Comments

0

I haven't tested this one but you could try this one. Replace the condition part of your code by this one. Though, there may be some performance issue.

if (Arr[i].trim().compareTo(Arr[j].trim())>0) {

Replace with:

if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {

The nthChar is the character placement to compare.

Comments

0

Here is sample tested code. You need to use comparator so as to implement the order. Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.

 String str[] = {"abc","bca","avc","ert"};
    final int ORDER = 1;
    Arrays.sort(str, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
           return o1.toLowerCase().charAt(ORDER) -  o2.toLowerCase().charAt(ORDER) ;
        }
    });

Comments

-1

Add different implementations of java.util.Comparator based on the requirement and use

public static <T> void sort(List<T> list, Comparator<? super T> c) in collections class to sort the list.

Comments

-2

You want to use a custom comparator.

1 Comment

sending a plain link is not a good answer, even if it's correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.