Java Collections
Java Collections
Java Collections
1. Comparable Interface
Given the list of Address details, sort them based on Pincode. If two address has the
same Pincode,
then sort them based on address line 1.
Solution:
import java.util.*;
class Address implements Comparable<Address> {
Address(){}
Address(String username, String addressLine1, String addressLine2,int
pinCode)
{
this.username=username;
this.addressLine1=addressLine1;
this.addressLine2=addressLine2;
this.pinCode =pinCode;
}
public String getusername() { return username; }
}
public String toString()
{
return username + "," + addressLine1 + "," + addressLine2 + "," + pinCode;
class Main {
public static void main(String[] args)
{
}
Collections.sort(list);
System.out.println("User Details:\n");
}
}
2. Email Search using set
Write a program to search all the email addresses which are given in CSV format.
Consider the Main class. Obtain email addresses from the user and add them to a
Set. At last, get a String that has multiple email addresses in CSV format. Print
"Email addresses are present" if all email addresses are present in the Set, else print
"Email addresses are not present".
Solution:
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Set<String> hash_Set = new HashSet<String>();
String c="yes";
while(c.compareTo("no")!=0)
{
System.out.println("Enter your Email Adress :");
hash_Set.add(sc.next());
System.out.println("Do you want to Continue?(yes/no)");
c=sc.next().toLowerCase();
}
System.out.println("Enter the email addresses to be searched separated by comma");
String str=sc.next();
String[] sp = str.split(",");
List<String> lp = Arrays.asList(sp);
HashSet<String> hash_Set2 = new HashSet<String>(lp);
if(hash_Set.containsAll(hash_Set2))
{
System.out.println("All Email addresses are present");
}
else{
System.out.println("Email addresses are not present");
for(String i : hash_Set2)
{
if(hash_Set.contains(i)!=true)
{
System.out.println(i);
}
}
}
}
}
3. Write a program to take hall objects as input in the list and sort them in the order
of their costPerDay using the sort() method of the comparable interface. Then
display them in tabular form. All class names, attribute names, and method names
should be the same as specified in the problem statement.
Solution:
import java.util.*;
class Hall implements Comparable<Hall> {
}
public String getName() { return name; }
class Main {
public static void main(String[] args)
{
ArrayList<Hall> list
= new ArrayList<Hall>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of halls:");
int n=sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++)
{
System.out.println("Enter the details of hall "+(i+1));
String[] sp=sc.nextLine().split(",");
list.add(new Hall(sp[0],sp[1],Double.valueOf(sp[2]),sp[3]));
}
Collections.sort(list);
System.out.println("\nSorted Order (from the least expensive to the
most):\n");
System.out.println("Name Contact number Costperday Owner name
");