0% found this document useful (0 votes)
59 views13 pages

Java Collection Operations Examples

The document contains 4 questions asking to write Java programs using various collections like ArrayList, LinkedList, TreeSet, HashMap. Question 1 asks to accept city names from the user, store in ArrayList and display. Question 2 asks to read friend names into LinkedList and display. Question 3 asks to add colors to TreeSet and display. Question 4 asks to create a HashMap to store student name and mobile number as key-value pairs and display the contact list.

Uploaded by

Shrushti Gurav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views13 pages

Java Collection Operations Examples

The document contains 4 questions asking to write Java programs using various collections like ArrayList, LinkedList, TreeSet, HashMap. Question 1 asks to accept city names from the user, store in ArrayList and display. Question 2 asks to read friend names into LinkedList and display. Question 3 asks to add colors to TreeSet and display. Question 4 asks to create a HashMap to store student name and mobile number as key-value pairs and display the contact list.

Uploaded by

Shrushti Gurav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q.

1) Write a java program to accept names of ‘n’ cities, insert same into an array list collection and
display the contents of the same array list, also remove all these elements.
[10]
*/
import [Link].*;
class Q1
{
public static void main ( String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("How many cities you want store : ");
int n = [Link]();
ArrayList <String> cities = new ArrayList <String> (n);
[Link]("Enter city names : ");
for ( int i = 0; i < n; i++ )
[Link]([Link]());
[Link] ( "City names are : ");
Iterator it = [Link]();
while([Link]())
[Link]([Link]());
[Link]();
[Link]("After removing all elements, size = " +[Link]());
[Link]();
}
}

b) Write a java program to read ‘n’ names of your friends, store it into linked list, also display contents of
the same.
*/
import [Link].*;
public class A2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

LinkedList<Object> ll = new LinkedList<>();


[Link]("Enter How many Friends :");
int n = [Link]();
[Link]("Enter the "+n+" Friends :");
[Link]();
for (int i = 0; i < n; i++) {
String fl = [Link]();
[Link](fl);
}
[Link]("Friends :" + ll);
[Link]();
}
}

c) Write a program to create a new tree set, add some colors (string) and print out the tree set.
import [Link];
import [Link];
public class A3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
TreeSet<Object> ts = new TreeSet<>();
[Link]("Enter How many Colours :");
int n = [Link]();
[Link]("Enter the "+n+" Colours :");
[Link]();
for (int i = 0; i < n; i++) {
String c = [Link]();
[Link](c);
}
[Link]("Colours :" + ts);
[Link]();
}
}

d) Create the hash table that will maintain the mobile number and student name.
Display the contact list.
import [Link].*;
class Q2
{
public static void main(String args[])
{

Hashtable <String, Long> contacts = new Hashtable < String, Long>();


[Link]("Vedang", 9324265714L);
[Link]("Pablo", 8124857238L);
[Link]("Chomp", 9871235677L);
/*Iterator<[Link] <String,Long>>it= [Link]().iterator();
[Link]<String,Long> e = null;
while([Link]())
{
e = [Link]();
[Link]([Link]()+ " " +[Link]());
}*/
for ([Link] <String, Long> e : [Link]())
{
[Link]([Link]()+ " "+[Link]());
}
}
}

SET B

a) Accept 'n' integers from the user. Store and display integers in sorted order having proper collection
class. The collection should not accept duplicate elements.

import [Link];

import [Link];

public class B1 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

TreeSet<Object> ts = new TreeSet<>();

[Link]("Enter how many Numbers: ");

int n = [Link]();

[Link]("Enter the " + n + " Numbers: ");

for (int i = 0; i < n; i++) {

int num = [Link]();

[Link](num);

[Link]("Numbers in Sorted Order and without Duplication :" + ts);

[Link]();

}
b) Write a program to sort HashMap by keys and display the details before sorting and after sorting.

import [Link];

import [Link];

public class B2 {

public static void main(String[] args) {

HashMap<String, Integer> map = new HashMap<>();

[Link]("Prasad", 2002);

[Link]("Ashish", 2001);

[Link]("Suhas", 2002);

[Link]("Swayam", 2001);

[Link]("Sanket", 2002);

[Link]("\nHashMap Details Before Sorting :\n" + map);

TreeMap<Object,Object> tm = new TreeMap<>(map);

[Link]("\nHashMap Details After Sorting :\n" + tm);

c) Write a program that loads names and phone numbers from a text file where the data is organized as
one line per record and each field in a record are separated by a tab (\t)or(:).it takes a name or phone
number as input and prints the corresponding other value from the hash table (hint: use hash tables).

import [Link].*;

import [Link].*;

public class Phonebook

public static void main(String args[])

try
{

FileInputStream fis=new FileInputStream("[Link]");

Scanner sc=new Scanner(fis).useDelimiter("\t");

Hashtable<String,String> ht=new Hashtable<String,String> ();

String[] strarray;

String a,str;

while([Link]())

a=[Link]();

strarray=[Link]("\t");

[Link](strarray[0],strarray[1]);

[Link]("hash table values are"+strarray[0]+":"+strarray[1]);

Scanner s=new Scanner([Link]);

[Link]("Enter the name as given in the phone book");

str=[Link]();

if([Link](str))

[Link]("phone no is"+[Link](str));

else

[Link]("Name is not matched");

}
catch(Exception e)

[Link](e);

Text File

prasad 8796465800

SET C

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

public class C1 extends JFrame implements ActionListener {

JTextField txtname, txtstd;

JButton btnadd, btndelete, btnsearch;

JPanel p1;

Hashtable<String, String> table = new Hashtable<>();

C1() {

setTitle("City STD Code Information");

setSize(700, 500);

setVisible(true);

setLayout(new GridLayout(3, 2, 20, 20));


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel name = new JLabel("Enter City Name: ");

add(name);

txtname = new JTextField(10);

add(txtname);

JLabel stdcode = new JLabel("Enter STD Code: ");

add(stdcode);

txtstd = new JTextField(10);

add(txtstd);

JLabel op = new JLabel("Choose Operation: ");

add(op);

p1 = new JPanel();

[Link](new GridLayout(1, 3, 5, 5));

btnadd = new JButton("Add");

[Link](btnadd);

[Link](this);

btndelete = new JButton("Delete");

[Link](btndelete);

[Link](this);

btnsearch = new JButton("Search");

[Link](btnsearch);

[Link](this);

add(p1);
}// SETC1

public void actionPerformed(ActionEvent ae) {

String name = ([Link]());

String std = ([Link]());

if ([Link]() == btnadd) {

// [Link]([Link](name) || [Link](std));

if ([Link](name) || [Link](std)) {

String s2 = "Duplicates are not allowded ";

[Link](null,s2,s2, JOptionPane.ERROR_MESSAGE);

} else {

[Link](name, std);

[Link](table);

[Link](null, "Succesfully Added City & STD Code", name,

JOptionPane.INFORMATION_MESSAGE);

[Link]("");

[Link]("");

if ([Link]() == btndelete) {

String s1 = [Link](null, "Enter City to remove");

[Link](s1);
[Link](null, "Succesfully removed City & STD Code", name,

JOptionPane.INFORMATION_MESSAGE);

if ([Link]() == btnsearch) {

String s1 = [Link](null, "Enter City");

if ([Link](s1)) {

String s2 = "STD Code: " + [Link](s1);

[Link](null, s2);

} else {

[Link](null, "ERROR OCCURED");

public static void main(String[] args) {

new C1();

b) Write a program to create link list of integer objects. Do the following:

* i. add element at first position

* ii. delete last element

* iii. display the size of link list


* */

import [Link];

import [Link];

public class C2 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

LinkedList<Object> ll = new LinkedList<>();

[Link](1);

[Link](2);

[Link](3);

[Link]("\nElements in List :\n" + ll);

[Link](0);

[Link]("\nList after adding Elements at First :\n" + ll);

[Link]();

[Link]("\nList after deleting Last Element :\n" + ll);

[Link]("\nSize of the List :\n" + [Link]());

[Link]();

c) Read a text file, specified by the first command line argument, into a list. The program should then
display a menu which performs the following operations on thelist:

* [Link] line 2. Delete line 3. Append line 4. Modify line 5. Exit

When the user selects Exit, save the contents of the list to the file and end the program.

import [Link].*;
import [Link].*;

public class C3 {

public static void main(String arg[]) {

Scanner sc = new Scanner([Link]);

try {

// Here, we have used command line argument , so at the time of run the code use
command java C3 [Link]

File f = new File(arg[0]);

BufferedReader br = null;

br = new BufferedReader(new FileReader(f));

FileOutputStream fout = new FileOutputStream(arg[0]);

int ch;

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

String line = "";

while ((line = [Link]()) != null) {

[Link](line);

} // while

// main logic

do {

[Link]("[Link] Line\[Link] Line\[Link] Line\[Link] Line\[Link]");

[Link]("Enter choice: ");

ch = [Link]();

String l1 = "This is a new Line";

switch (ch) {

case 1:

[Link](l1);
break;

case 2:

[Link](l1);

break;

case 3:

[Link](l1);

break;

case 4:

int n = [Link]() - 1;

[Link](n, "\tUpdated line");

break;

case 5:

ListIterator<Object> li = [Link]();

while ([Link]()) {

String l2 = (String) [Link]();

byte b[] = [Link]();

[Link](b);

[Link](1);

break;

} while (ch < 6);

[Link]();

[Link]();

} catch (Exception e) {
[Link](e);

[Link]();

Text File

This is a new Line Updated lineJ

Common questions

Powered by AI

Handling exceptions when reading from a text file in Java is crucial because it allows for graceful error handling, such as dealing with cases where a file might not exist, the file cannot be read due to missing permissions, or an unexpected error occurs while processing the file. Without proper exception handling, the application could terminate abruptly, leading to a poor user experience or potential data loss.

TreeMap provides advantages over HashMap when sorted order of elements is required. TreeMap maintains the natural order of its keys or allows for a custom comparator during initialization, thus facilitating sorted data retrieval. Additionally, TreeMap offers log(n) time complexity for insertion and lookup due to its underlying tree structure, whereas HashMap offers O(1) for these operations but without any ordering guarantees.

Duplicates can be prevented in a Java Set collection because Set implementations inherently do not allow duplicate entries. Specifically, HashSet, LinkedHashSet, and TreeSet are implementations of the Set interface in Java that ensure no duplicate elements are stored. This is achieved by using a hashing mechanism for HashSet and LinkedHashSet, and a red-black tree for TreeSet to maintain unique elements.

Using a TreeSet would be more advantageous than a HashSet when you need to maintain a sorted set of elements. TreeSet maintains order through a red-black tree structure, which means elements can be retrieved in sorted order, providing O(log n) time complexity for the basic operations (add, remove, and contains) compared to HashSet which offers O(1) for these operations but does not maintain order.

A LinkedList is more appropriate than an ArrayList when rapid insertions and deletions of elements from the beginning or middle of the list are needed. This is because a LinkedList is a doubly-linked list, which allows for constant time complexity for such operations, requiring only a reassignment of pointers, unlike an ArrayList where elements have to be shifted, resulting in a linear time complexity for these operations.

A potential drawback of using HashTable is that it is synchronized, meaning it is thread-safe, which may not be necessary in single-threaded applications and can result in unnecessary computational overhead. Other map implementations like HashMap or ConcurrentHashMap provide similar functionalities with less synchronization overhead, making them preferable for non-threaded or read-heavy concurrent applications.

The Java ArrayList is generally faster for adding elements to the end of the list and accessing elements by index compared to LinkedList as it is backed by an array. However, when it comes to removing elements, especially from the beginning or the middle of the list, a LinkedList provides better performance because it is a doubly-linked list, allowing for constant time insertions or removals using iterators.

Not closing resources such as Scanner and BufferedReader in Java applications can lead to memory leaks and resource exhaustion. These resources consume system-level resources, and failing to close them implies that those resources remain allocated, potentially leading to a performance bottleneck or system resource starvation, especially in long-running applications. Properly closing these resources ensures efficient resource management and system stability.

Java Swing can be utilized to create a user interface for handling dynamic data operations through components like JTextFields for input, JButtons for operations, and JLabels for displaying results. For example, a user interface can be designed to allow users to add, delete, or search student records stored in a hash table, using event listeners to handle user actions on buttons. This provides an interactive interface for managing dynamic datasets seamlessly within an application.

CRUD operations can be implemented on a list of strings in Java by loading the strings into an ArrayList from a file. "Create" can be performed by inserting new strings; "Read" by displaying current elements; "Update" by modifying existing strings; and "Delete" by removing elements. The benefits of using an ArrayList include dynamic resizing, fast access (via index), and ease of iteration, making it suitable for manipulating collections of data that require frequent changes.

You might also like