Find The Length of Array List

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

1.

Find the length of array list:


ArrayList<Integer> al=new ArrayList<Integer>();

System.out.println("Initial size: "+al.size());

al.add(1);
al.add(13);
al.add(45);
al.add(44);
al.add(99);

System.out.println("Size after few additions: "+al.size());

al.remove(1);
al.remove(2);

System.out.println("Size after remove operations: "+al.size());

System.out.println("Final ArrayList: ");

for(int num: al){


System.out.println(num);

Output:

Initial size: 0
Size after few additions: 5
Size after remove operations: 3
Final ArrayList:
1
45
99

2. Sort Array List:


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

listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");

/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}

/* Sort statement*/
Collections.sort(listofcountries);
/* Sorted List*/
System.out.println("After Sorting:");

for(String counter: listofcountries){


System.out.println(counter);
}

Output:

Before Sorting:
India
US
China
Denmark
After Sorting:
China
Denmark
India
US

3. Sort Integer array list:


ArrayList<Integer> arraylist = new ArrayList<Integer>();

arraylist.add(11);
arraylist.add(2);
arraylist.add(7);
arraylist.add(3);

/* ArrayList before the sorting*/


System.out.println("Before Sorting:");

for(int counter: arraylist){


System.out.println(counter);
}

/* Sorting of arraylist using Collections.sort*/


Collections.sort(arraylist);

/* ArrayList after sorting*/


System.out.println("After Sorting:");

for(int counter: arraylist){


System.out.println(counter);
}

Output:

Before Sorting:
11
2
7
3
After Sorting:
2
3
7
11

4. Sort array list in descending order

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

arraylist.add("AA");
arraylist.add("ZZ");
arraylist.add("CC");
arraylist.add("FF");

/*Unsorted List: ArrayList content before sorting*/


System.out.println("Before Sorting:");

for(String str: arraylist){


System.out.println(str);
}

/* Sorting in decreasing order*/


Collections.sort(arraylist, Collections.reverseOrder());

/* Sorted List in reverse order*/


System.out.println("ArrayList in descending order:");

for(String str: arraylist){


System.out.println(str);
}

Output:

Before Sorting:
AA
ZZ
CC
FF
ArrayList in descending order:
ZZ
FF
CC
AA

You might also like