Monday, 10 March 2025

Write a java program to read n Empoyee names from user, store them into the Array List collection. The program should not allow duplicate names. Display the names in Ascending order.



import java.util.*;

class EmployeeNames

{

    public static void main(String args[])

    {

        Scanner sc = new Scanner(System.in);

        ArrayList<String> names = new ArrayList<>();


        System.out.print("Enter number of employees: ");

        int n = sc.nextInt();

        sc.nextLine();


        for(int i = 0; i < n; i++)

        {

            System.out.print("Enter employee name: ");

            String name = sc.nextLine();


            // Add only if not already present

            if(!names.contains(name))

            {

                names.add(name);

            }

        }


          Collections.sort(names);

        System.out.println("Employee Names in Ascending Order:");

        System.out.println(names);


        sc.close();

    }

}




Second Method

import java.util.*;

import java.io.*;

public class EmployeeArray

{

public static void main(String args[])throws Exception

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

ArrayList a = new ArrayList();

System.out.println("\nEnter number of Employee : ");

int n = Integer.parseInt(br.readLine());

System.out.println("\nEnter name : ");

for(int i = 1; i <= n; i++)

{

a.add(br.readLine());

}

TreeSet tr = new TreeSet(a);

System.out.println("Sorted name are : "+tr);

}

}