Java Programing laungage

java.util Projects

java.util Project 1

Shuffling the Element of ArrayList

Shuffling is the technique which is used to randomize the element of arrayList to prepare each and every element for the operation. In this section, you will learn about shuffling the element of a arraylist. Shuffling the element means transfer the element from one place to another place randomly.

Previous Home Next

In this program, The list is created which hold some values. This program takes some values from the list and it sorts these values after shuffling. For performing this task we can used some methods and APIs, which is explained below.

List

It is the class of java.util.*; package which extends Collection.

ArrayList()

It is used to constructs an empty list. we can specify the capacity of the list by passing a value to the constructor.

sort(list)

This is the method of the Collections class which is used to sort the list elements in the default order.

Example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class sufflingtest {
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements you want to add: ");
int n = Integer.parseInt(br.readLine());
System.out.print("Enter " + n + " numbers for sorting: ");
List<Integer> lst = new ArrayList<Integer>();
for(int i = 0; i < n; i++){
lst.add(Integer.parseInt(br.readLine()));
}
Collections.shuffle(lst);
Collections.sort(lst);
System.out.println("List sorting :"+ lst);
}
}

Previous Home Next