0% found this document useful (0 votes)
61 views29 pages

Collection Programs

The document contains multiple Java programs demonstrating the use of various collection frameworks including ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, and HashMap. Each program illustrates different functionalities such as adding, removing, and iterating over elements, as well as handling duplicates and conversions between collections. The document serves as a comprehensive guide for understanding and utilizing Java collections effectively.

Uploaded by

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

Collection Programs

The document contains multiple Java programs demonstrating the use of various collection frameworks including ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, and HashMap. Each program illustrates different functionalities such as adding, removing, and iterating over elements, as well as handling duplicates and conversions between collections. The document serves as a comprehensive guide for understanding and utilizing Java collections effectively.

Uploaded by

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

Collection programs

Program for AL
import [Link];
import [Link];
import [Link];

public class app {


public static void main(String[] args) {
ArrayList al = new ArrayList();
[Link](10);
[Link](1450);
[Link]("shekar");
[Link](10);
[Link]("shekar");
[Link](true);
[Link](1);
[Link]("size : " + [Link]());
[Link]("isEmpty : " + [Link]());
[Link]("contains : " + [Link]("shekar"));
[Link]("contains : " + [Link](1450));
[Link]("get IndexOf : " + [Link](al));

// returns first occurence index


[Link]("get IndexOf : " + [Link](10));
LinkedList ll = new LinkedList(al); //converted to LL
[Link]("converted to Linkedlist "+ll);

Object l = [Link](); // We can convert AL to Object


// LinkedList ll=(LinkedList)[Link]();
// [Link] cannot be cast to class [Link]

[Link]("Linked list : " + l);

[Link]("last index is : " + [Link]("shekar"));

Object[] o = [Link]();
int i = 1;
for (Object object : o) {
[Link](i + " - " + object);
i++;
}

[Link]("getting elements using its index : " + [Link](1));


[Link](1, 999);
[Link]("after setting element by set() : " + [Link](1));
[Link](5, 12.3);
[Link]("accessing 5th element which added by add(i,E) :
" + [Link](5));
[Link]("before removing : " + al);
[Link](1);// here in this case : it is taking as index number not
element-1
[Link]("shekar");// removes first occurence element if we have
multiple same elements
[Link]("after removing : " + al);

// ArrayList list=new ArrayList(al);


ArrayList list = new ArrayList();
[Link](al);// using addAll()
[Link]("checking two objects are equal : " +
[Link](list));
[Link]("checking two objects are equal : " + [Link](l));
[Link](al);
[Link]("After using removeAlL() checking two objects are
equal : " + [Link](list));

[Link]("hashcode is : " + [Link]());


[Link]();
[Link]("after clear() : " + al);
}
}
Program for LL :

import [Link];
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
[Link](10);
[Link]("shekar");
[Link](13);
[Link](true);
[Link]("shekar");
[Link]("initial LL : " + ll);

// peek() and getFirst() and element() and peekFirst() same but :


// peek() Returns null if the linked list is empty. ie., null
// getFirst() gives NoSuchElementException if the linked list is empty.
i.e., :
// [Link]
// element() throws a NoSuchElementException if the linked list is
empty. i.e.,
// [Link]
// peekFirst() Returns null if Empty
[Link]("getting 1st element : " + [Link]());

// peekLast() Returns Last Element.


// peekLast() Returns null if Empty.
[Link]("getting last element : " + [Link]());

// poll(),pollFirst() and removeFirst() are same but,


// removeFirst() Throws NoSuchElementException if the linked list is
empty.
// pollFirst() Returns null if the linked list is empty.
// poll() Returns null if the linked list is empty.
// pop() same as removeFirst()
[Link]();
[Link]("after removing first element : " + ll);

// pollLast() and removeLast() are same but,


// pollLast() Returns null if the linked list is empty.
// removeLast() Throws NoSuchElementException if the linked list is
empty.
[Link]();
[Link]("after removing last element : " + ll);

// offer(), offerFirst(),offerLast() vs add(), addFirst(), and addLast()


// all are same but offer methods Returns true if the element was
added
// successfully, otherwise false.
// push() same as addFirst()
[Link](1);
[Link]("after adding element at first : " + ll);

[Link]("last");
[Link]("after adding element at last : " + ll);

[Link](100); // Adds elements to last


[Link]("after adding using aad() : " + ll);

[Link](3, "third");
[Link]("after adding element at 3rd index : " + ll);

[Link]("using contains() : " + [Link]("shekar"));

[Link]("getting size() : " + [Link]());

LinkedList copy = new LinkedList();


[Link](ll);
[Link]("copied LL using addAll() : " + copy);
// lly there are removeFirstOccurence() and removeLastOccurence()
Removes the
// last/first occurrence of the specified element from the linked list
[Link]("last");
[Link]("after removing 'last' element : " + ll);

[Link](0);
[Link]("removed 0th index : " + ll);

[Link]("getting index[1] : " + [Link](1));

[Link](4, "hundred");
[Link]("setting 4th element using set(i,E) : " + ll);

[Link]("index of 'shekar' is : " + [Link]("shekar"));


[Link]("index of 'shekar' is : " + [Link]("shekar"));

//clone() -->gives copy of LL


//toArray --> used to convert a linked list to an array.
// Object[] array = [Link]();
[Link]();
[Link]("done : "+ll);

}
}
Progam for Iterstor
import [Link];
import [Link];
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList<>();
[Link](10);
[Link]("shekar");
[Link](13);
[Link](true);
[Link]("shekar");
String s = (String) [Link](1);
[Link](s);
int i = (Integer) [Link](0);
[Link](i);
Iterator itr = [Link]();
while([Link]())
{
[Link]("element is : "+[Link]());
}
}
}
Progam for Iterstor
import [Link];
import [Link];
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList<>();
[Link](10);
[Link]("shekar");
[Link](13);
[Link](true);
[Link]("shekar");
String s = (String) [Link](1);
[Link](s);
int i = (Integer) [Link](0);
[Link](i);
ListIterator itr = [Link]();
while([Link]())
{
[Link]("index is : "+[Link]());
[Link]("element is : "+[Link]());
}
}
}
Pogram to get non-duplicate/repeating characters from a
string

import [Link];
import [Link];
public class dup {
public static void main(String[] args) {
dupWithoutInbuilt();// giving op but not in alphabetial order or same
order
dupWithHashSet(); // giving in alphabetical order
}
private static void dupWithHashSet() {
String s = "adabegggfFFDVa";
HashSet<Character> h = new HashSet();
char[] c = [Link]();
for (int i = 0; i < [Link]; i++) {
[Link](c[i]);
// [Link](c[i]);
}
for (Character d : h) {
[Link](d);
}
}
private static void dupWithoutInbuilt() {
Scanner sc = new Scanner([Link]);
String s = [Link]();
StringBuilder sb = new StringBuilder();
char[] cs = [Link]();
char[] ch = new char[[Link]];
for (int i = 0; i < [Link]; i++) {
boolean b = false;
for (int j = i + 1; j < [Link]; j++) {
if (cs[i] == cs[j]) {
b = true;
break;
}
}
if (!b) {
[Link](cs[i]);
}
}
[Link](sb);
}
}
Program for HashSet…

package test;import [Link];


import [Link];
import [Link];

public class app {


public static void main(String[] args) {
// Create a HashSet
HashSet<String> myHashSet = new HashSet<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Grapes");

// Displaying the HashSet


[Link]("HashSet: " + myHashSet);

// Size of the HashSet


[Link]("Size of HashSet: " + [Link]());

// Checking for element existence


[Link]("Contains 'Apple': " + [Link]("Apple"));
[Link]("Contains 'Mango': " + [Link]("Mango"));

// Removing an element
[Link]("Orange");
[Link]("HashSet after removing 'Orange': " + myHashSet);

// Iterating through the HashSet using Iterator


Iterator<String> iterator = [Link]();
[Link]("Elements using Iterator:");
while ([Link]()) {
[Link]([Link]());
}

// Using SplitIterator (Not a typical use-case for HashSet, shown for reference)
Spliterator<String> spliterator = [Link]();
[Link]("Elements using Spliterator:");
[Link]([Link]::println);

// Clone the HashSet


HashSet<String> clonedHashSet = (HashSet<String>) [Link]();
[Link]("Cloned HashSet: " + clonedHashSet);

// Convert HashSet to array


Object[] arrayFromHashSet = [Link]();
[Link]("Array from HashSet:");
for (Object obj : arrayFromHashSet) {
[Link](obj);
}

// Clearing the HashSet


[Link]();
[Link]("HashSet after clear(): " + myHashSet);
}
}
package test;import [Link];
import [Link];
import [Link];

public class app {


public static void main(String[] args) {
// Create a HashSet
HashSet<String> myHashSet = new HashSet<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Grapes");

// Displaying the HashSet


[Link]("HashSet: " + myHashSet);

// Size of the HashSet


[Link]("Size of HashSet: " + [Link]());

// Checking for element existence


[Link]("Contains 'Apple': " + [Link]("Apple"));
[Link]("Contains 'Mango': " + [Link]("Mango"));

// Removing an element
[Link]("Orange");
[Link]("HashSet after removing 'Orange': " + myHashSet);

// Iterating through the HashSet using Iterator


Iterator<String> iterator = [Link]();
[Link]("Elements using Iterator:");
while ([Link]()) {
[Link]([Link]());
}

// Using SplitIterator (Not a typical use-case for HashSet, shown for reference)
Spliterator<String> spliterator = [Link]();
[Link]("Elements using Spliterator:");
[Link]([Link]::println);

// Clone the HashSet


HashSet<String> clonedHashSet = (HashSet<String>) [Link]();
[Link]("Cloned HashSet: " + clonedHashSet);

// Convert HashSet to array


Object[] arrayFromHashSet = [Link]();
[Link]("Array from HashSet:");
for (Object obj : arrayFromHashSet) {
[Link](obj);
}

// Clearing the HashSet


[Link]();
[Link]("HashSet after clear(): " + myHashSet);
}
}
Program for LinkedHashSet

import [Link];
import [Link];

public class app {


public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Grapes");

// Displaying the LinkedHashSet


[Link]("LinkedHashSet: " + linkedHashSet);

// Size of the LinkedHashSet


[Link]("Size: " + [Link]());

// Iterating through the LinkedHashSet using Iterator


[Link]("Elements using Iterator:");
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}

// Checking if an element exists


[Link]("Contains 'Orange'? " +
[Link]("Orange"));

// Removing an element
[Link]("Banana");

// Clearing the LinkedHashSet


[Link]();

// Checking if the set is empty after clearing


[Link]("Is LinkedHashSet empty? " +
[Link]());
}
}
Program for TreeHashSet

import [Link];
import [Link];

public class TreeSetExample {


public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Grapes");

// Displaying the TreeSet


[Link]("TreeSet: " + treeSet);

// Size of the TreeSet


[Link]("Size: " + [Link]());

// Iterating through the TreeSet using Iterator


[Link]("Elements using Iterator:");
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}

// Checking if an element exists


[Link]("Contains 'Orange'? " + [Link]("Orange"));

// Removing an element
[Link]("Banana");

// Clearing the TreeSet


[Link]();

// Checking if the set is empty after clearing


[Link]("Is TreeSet empty? " + [Link]());
}
}
Program for HashMap

import [Link].*;
public class app {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "shekar");
[Link](2, "raja");
[Link](3, "eddandi");
[Link](1, "sheki");
[Link](map);
Set<Integer> keys=[Link]();
for (Integer integer : keys) {
[Link]("key is : "+integer);
}
for (Integer integer : keys) {
[Link]("key is +: "+integer+" value is :
"+[Link](integer));
}
Collection<String> s= [Link]();
[Link](s);
}
}
Second program for HAshMap

import [Link];
import [Link];

public class HashMapExample {


public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> hashMap = new HashMap<>();

// Adding key-value pairs


[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 28);
[Link]("David", 35);

// Accessing elements
[Link]("Age of Alice: " + [Link]("Alice"));

// Iterating through the HashMap


[Link]("\nIterating through the HashMap:");
for ([Link]<String, Integer> entry : [Link]()) {
[Link]("Name: " + [Link]() + ", Age: " + [Link]());
}
// Checking if a key exists
String searchKey = "Bob";
if ([Link](searchKey)) {
[Link]("\n" + searchKey + " is present. Age: " +
[Link](searchKey));
} else {
[Link]("\n" + searchKey + " is not present in the HashMap.");
}

// Removing a key-value pair


[Link]("Charlie");
[Link]("\nAfter removing Charlie:");
for ([Link]<String, Integer> entry : [Link]()) {
[Link]("Name: " + [Link]() + ", Age: " + [Link]());
}

// Clearing the HashMap


[Link]();
[Link]("\nHashMap has been cleared. Size: " + [Link]());
}
}
In Java, there are several ways to get the keys and values of a
`HashMap`.

### Getting Keys:

1. **`keySet()` Method:**
- `keySet()` returns a `Set` containing all the keys in the `HashMap`.

- Example:
Map<String, Integer> hashMap = new HashMap<>();
// Add some key-value pairs...
Set<String> keys = [Link]();

2. **`forEach()` Method with `keySet()`:**


- You can iterate over the keys using `forEach` and `keySet()`.

Example:
[Link]().forEach(key -> {
// Access each key
});

### Getting Values:


1. **`values()` Method:**
- `values()` returns a `Collection` of all the values in the `HashMap`.

- Example:
Collection<Integer> values = [Link]();

2. **`forEach()` Method with `values()`:**


- You can iterate over the values using `forEach` and `values()`.

- Example:
[Link]().forEach(value -> {
// Access each value
});

3. **`entrySet()` Method:**
- `entrySet()` returns a `Set` of `[Link]` objects containing both keys and
values.

- Example:
Set<[Link]<String, Integer>> entries = [Link]();
for ([Link]<String, Integer> entry : entries) {
String key = [Link]();
Integer value = [Link]();
// Process key and value
}
```

Each of these approaches has its advantages based on what you intend to do with
the keys and values of the `HashMap`. You can choose the method that best fits
your specific use case.

PROGRAM to Explaining Clone() by generating equals() and


hashCode()

import [Link];
public class app {
public static void main(String[] args) throws CloneNotSupportedException {

shekar s = new shekar(1, "shekar");


shekar s1 = new shekar(1, "shekar");
Object o = [Link]();
[Link]([Link](o));
}

class shekar implements Cloneable {


int a;
String b;

public shekar(int a, String b) {


super();
this.a = a;
this.b = b;
}

@Override
public int hashCode() {
return [Link](a, b);
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
shekar other = (shekar) obj;
return a == other.a && [Link](b, other.b);
}

@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return [Link]();
}

Program using toString() by overriding toString()

package test;

import [Link];

public class app {


int a, b;

public app(int a, int b) {


super();
this.a = a;
this.b = b;
}

public static void main(String[] args) {

app p = new app(0, 20);


[Link](p);
[Link]([Link]());
}

@Override
public String toString() {
return "app [a=" + a + ", b=" + b + "]";
}

You might also like