0

I found this code which was meant to avoid duplicate values for numbers so I changed it to consider String elements.It successfully avoids duplicate names when printing, but it does not sort the names in alphabetic order.

I also hope that it does not print a specific element "vacant", because it will be later updated with a name through an input.

This is based on a booking system to sort names in ascending order,so empty elements are called "vacant".
Please can someone help me.

String[] a ={"Anne","Anne","Afrid","vacant","vacant","Sammy","Dora","vacant"};
HashSet<String> nameSet = new HashSet<>();
for (int i = 0; i < a.length;i++){
    nameSet.add(a[i]);
}
for (String name: nameSet) {
    System.out.println(name+" ");
}
Bashir
  • 2,057
  • 5
  • 19
  • 44
Genesis_Kitty
  • 63
  • 2
  • 7
  • My first thought is to store the names in an `ArrayList` instead and let it take care of the vacant elements. In any case, if you use `TreeSet` instead of `HashSet`, the elements will be sorted. Then you just need to check `! name.equals("vacant")` in the loop where you print the names. – Ole V.V. Mar 16 '20 at 14:07

1 Answers1

0

Here is a simple code to do the following,

  1. Removed duplicates
  2. Removed Vacant
  3. Removes anything that has null
  4. Sorts the list ignore case
  5. Prints them
    public static void main(String argv[]) {
        //Input
        String[] a = { "Anne", "Anne", "Afrid", "vacant", "vacant", "Sammy", "Dora", "vacant" };
        List<String> list = Stream.of(a) //Convert to Stream
                .filter(Objects::nonNull) //Remove Null values
                .sorted(new IgnoreCaseStringSorter()) //Sort ignore case
                .distinct() //Remove duplicates
                .filter(name -> !name.equalsIgnoreCase("vacant")) //Remove "vacant"
                .collect(Collectors.toList()); //Convert to list
        System.out.println("Names: ");
        list.stream().forEach(System.out::println);//Print the list

    }
    static class IgnoreCaseStringSorter implements Comparator<String> {
        // Used for sorting in ascending order
        public int compare(String a, String b) {
            return a.compareToIgnoreCase(b);
        }
    }

Output:

Names: 
Afrid
Anne
Dora
Sammy

reflexdemon
  • 836
  • 8
  • 21