Thursday, February 11, 2016

Java Programs On Collections and Arrays

In this Post we will discuss Java Programs on Collections and Arrays.These programs are frequently asked in interviews and written test as well.I already posted 
Arrays in java with example

Program 1: How to sort elements of Array

import java.util.Arrays;
import java.util.Comparator;
class ArraysSortDemo
{
public static void main(String args[])
{
int [] a={10,5,20,11,6};

System.out.println("primitive array before sorting:");
for(int a1:a)
{
System.out.println(a1);
}
Arrays.sort(a);
System.out.prinltn("primitive array after sorting");
for(int a1:a)
{
System.out.println(a1);
}
String[] s={"A","Z","B"};
System.out.println("object array before sorting");
for(String a2:s)
{
System.out.println(a2);
}
Arrays.sort(s);
System.out.println("object array after sorting");
for(String a1:s)
{
System.out.println(a1);
}
Arrays.sort(s,new MyComparator());
System.out.println("object array after sorting by comparator:");
for(String a1:s)
{
System.out.println(a1);
}
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}
}

Output:




Program 2: How To Search Elements of List

import java.util.*;
class CollectionSearchDemo
{
public static void main(String [] args)
{
ArraysList al=new ArrayList();
al.add("apple");
al.add("mango");
al.add("banana");
al.add("grape");
System.out.println(al);
//Collections.sort(al);
System.out.println(al);
System.out.println(Collections.birnarySearch(al,"apple"));
System.out.println(Collections.birnarySearch(al,"mango"));
}
}

Output:




Program 3: How to Reverse Elements of List

import java.util.*;
class CollectionReverseDemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(15);
al.add(0);
al.add(45);
al.add(10);
System.out.println(al);
Collections.reverse(al);
System.out.println(al);
}
}

Output:




Program 4:  How to View Array in List Form

import java.util.*;
class ArraysAsListDemo
{
public static void main(String args[])
{
String[] s={"A","Z","B"};
List l= Arrays.asList(s);//[A,Z,B]
s[0]="k";
System.out.println(l);//[K,Z,B]
l.set(1,"L");
for(String s1:s)
System.out.println(s1);//K,L,B
//l.add("lucky"); UnSupportedOperationException
//l.remove(2);     UnSupportedOperationException
}
}

Output:


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...