Java Program to create a List and perform functions using Collections

    A set of elements grouped together under a common name is called a collection. To implement this, a package “java.util” is used. This package has many static methods and operates the collections.

Collections has some set of operations like reverse, search and sorting. Let us list the some of methods in the ‘Collections’ class.

Java Program to create a List and perform functions using Collections:

This program starts by importing the header files and has following steps.

Steps:

  • A public class is created with main() function.
  • A list object list1 is created as integer ArrayList.
  • To insert the values, use add() function.
  • Print the newly created list.
  • Now, sort the elements by sort() function using Collections.
  • Print the sorted list.
  • To search an element using binary search, a function binarySearch() is used.
  • It display the key position as output.
  • Next,the list is reversed using reverse() function.
  • The list is printed after the reversal.
  • To shuffle the data at random, a function shuffle() is used.
  • Finally, the list is displayed after shuffled.

Program:

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class CollEg1 {

    public static void main(String[] args) {

        // A list is created here

        List<Integer> list1 = new ArrayList<>();     

        // Let us add the elements to the list

        list1.add(43);

        list1.add(81);

        list1.add(25);

        list1.add(12);

        list1.add(56);

        System.out.println("The original list is:" + list1);

        //Sorting the list using collections

        Collections.sort(list1);

        // Display the list

        System.out.println("The Sorted List is: " + list1);

        //Searching an element using Binary Search

        int a =Collections.binarySearch(list1,25);

        System.out.println("The key is at Position :"+ a);

      //Reverse the list

        Collections.reverse(list1);

        //Print the list after reverse

        System.out.println("The Reversed List is: " + list1);

        //Shuffle the list

        Collections.shuffle(list1);

        //Print the list after shuffling

        System.out.println("The shuffled List is: " + list1);

            }

}

Output:

C:\raji\blog>javac CollEg1.java

C:\raji\blog>java CollEg1

The original list is:[43, 81, 25, 12, 56]

The Sorted List is: [12, 25, 43, 56, 81]

The key is at Position :1

The Reversed List is: [81, 56, 43, 25, 12]

The shuffled List is: [81, 25, 43, 56, 12]

This is the simple way of creating a list and perform operations using Collections. Hope you understand it. Keep coding!!!

No comments:

Post a Comment