Collection programs
Program for AL
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
public class app {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);
al.add(1450);
al.add("shekar");
al.add(10);
al.add("shekar");
al.add(true);
al.add(1);
System.out.println("size : " + al.size());
System.out.println("isEmpty : " + al.isEmpty());
System.out.println("contains : " + al.contains("shekar"));
System.out.println("contains : " + al.contains(1450));
System.out.println("get IndexOf : " + al.indexOf(al));
// returns first occurence index
System.out.println("get IndexOf : " + al.indexOf(10));
LinkedList ll = new LinkedList(al); //converted to LL
System.out.println("converted to Linkedlist "+ll);
Object l = al.clone(); // We can convert AL to Object
// LinkedList ll=(LinkedList)al.clone();
// java.util.ArrayList cannot be cast to class java.util.LinkedList
System.out.println("Linked list : " + l);
System.out.println("last index is : " + al.lastIndexOf("shekar"));
Object[] o = al.toArray();
int i = 1;
for (Object object : o) {
System.out.println(i + " - " + object);
i++;
}
System.out.println("getting elements using its index : " + al.get(1));
al.set(1, 999);
System.out.println("after setting element by set() : " + al.get(1));
al.add(5, 12.3);
System.out.println("accessing 5th element which added by add(i,E) :
" + al.get(5));
System.out.println("before removing : " + al);
al.remove(1);// here in this case : it is taking as index number not
element-1
al.remove("shekar");// removes first occurence element if we have
multiple same elements
System.out.println("after removing : " + al);
// ArrayList list=new ArrayList(al);
ArrayList list = new ArrayList();
list.addAll(al);// using addAll()
System.out.println("checking two objects are equal : " +
al.equals(list));
System.out.println("checking two objects are equal : " + al.equals(l));
list.removeAll(al);
System.out.println("After using removeAlL() checking two objects are
equal : " + al.equals(list));
System.out.println("hashcode is : " + al.hashCode());
al.clear();
System.out.println("after clear() : " + al);
}
}
Program for LL :
import java.util.LinkedList;
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(10);
ll.add("shekar");
ll.add(13);
ll.add(true);
ll.add("shekar");
System.out.println("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., :
// java.util.NoSuchElementException
// element() throws a NoSuchElementException if the linked list is
empty. i.e.,
// java.util.NoSuchElementException
// peekFirst() Returns null if Empty
System.out.println("getting 1st element : " + ll.getFirst());
// peekLast() Returns Last Element.
// peekLast() Returns null if Empty.
System.out.println("getting last element : " + ll.getLast());
// 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()
ll.removeFirst();
System.out.println("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.
ll.removeLast();
System.out.println("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()
ll.addFirst(1);
System.out.println("after adding element at first : " + ll);
ll.addLast("last");
System.out.println("after adding element at last : " + ll);
ll.add(100); // Adds elements to last
System.out.println("after adding using aad() : " + ll);
ll.add(3, "third");
System.out.println("after adding element at 3rd index : " + ll);
System.out.println("using contains() : " + ll.contains("shekar"));
System.out.println("getting size() : " + ll.size());
LinkedList copy = new LinkedList();
copy.addAll(ll);
System.out.println("copied LL using addAll() : " + copy);
// lly there are removeFirstOccurence() and removeLastOccurence()
Removes the
// last/first occurrence of the specified element from the linked list
ll.remove("last");
System.out.println("after removing 'last' element : " + ll);
ll.remove(0);
System.out.println("removed 0th index : " + ll);
System.out.println("getting index[1] : " + ll.get(1));
ll.set(4, "hundred");
System.out.println("setting 4th element using set(i,E) : " + ll);
System.out.println("index of 'shekar' is : " + ll.indexOf("shekar"));
System.out.println("index of 'shekar' is : " + ll.lastIndexOf("shekar"));
//clone() -->gives copy of LL
//toArray --> used to convert a linked list to an array.
// Object[] array = ll.toArray();
ll.clear();
System.out.println("done : "+ll);
}
}
Progam for Iterstor
import java.util.Iterator;
import java.util.LinkedList;
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList<>();
ll.add(10);
ll.add("shekar");
ll.add(13);
ll.add(true);
ll.add("shekar");
String s = (String) ll.get(1);
System.out.println(s);
int i = (Integer) ll.get(0);
System.out.println(i);
Iterator itr = ll.iterator();
while(itr.hasNext())
{
System.out.println("element is : "+itr.next());
}
}
}
Progam for Iterstor
import java.util.LinkedList;
import java.util.ListIterator;
public class app {
public static void main(String[] args) {
LinkedList ll = new LinkedList<>();
ll.add(10);
ll.add("shekar");
ll.add(13);
ll.add(true);
ll.add("shekar");
String s = (String) ll.get(1);
System.out.println(s);
int i = (Integer) ll.get(0);
System.out.println(i);
ListIterator itr = ll.listIterator();
while(itr.hasNext())
{
System.out.println("index is : "+itr.nextIndex());
System.out.println("element is : "+itr.next());
}
}
}
Pogram to get non-duplicate/repeating characters from a
string
import java.util.HashSet;
import java.util.Scanner;
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 = s.toCharArray();
for (int i = 0; i < c.length; i++) {
h.add(c[i]);
// System.out.println(c[i]);
}
for (Character d : h) {
System.out.print(d);
}
}
private static void dupWithoutInbuilt() {
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuilder sb = new StringBuilder();
char[] cs = s.toCharArray();
char[] ch = new char[cs.length];
for (int i = 0; i < cs.length; i++) {
boolean b = false;
for (int j = i + 1; j < cs.length; j++) {
if (cs[i] == cs[j]) {
b = true;
break;
}
}
if (!b) {
sb.append(cs[i]);
}
}
System.out.println(sb);
}
}
Program for HashSet…
package test;import java.util.HashSet;
import java.util.Iterator;
import java.util.Spliterator;
public class app {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> myHashSet = new HashSet<>();
// Adding elements
myHashSet.add("Apple");
myHashSet.add("Banana");
myHashSet.add("Orange");
myHashSet.add("Grapes");
// Displaying the HashSet
System.out.println("HashSet: " + myHashSet);
// Size of the HashSet
System.out.println("Size of HashSet: " + myHashSet.size());
// Checking for element existence
System.out.println("Contains 'Apple': " + myHashSet.contains("Apple"));
System.out.println("Contains 'Mango': " + myHashSet.contains("Mango"));
// Removing an element
myHashSet.remove("Orange");
System.out.println("HashSet after removing 'Orange': " + myHashSet);
// Iterating through the HashSet using Iterator
Iterator<String> iterator = myHashSet.iterator();
System.out.println("Elements using Iterator:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using SplitIterator (Not a typical use-case for HashSet, shown for reference)
Spliterator<String> spliterator = myHashSet.spliterator();
System.out.println("Elements using Spliterator:");
spliterator.forEachRemaining(System.out::println);
// Clone the HashSet
HashSet<String> clonedHashSet = (HashSet<String>) myHashSet.clone();
System.out.println("Cloned HashSet: " + clonedHashSet);
// Convert HashSet to array
Object[] arrayFromHashSet = myHashSet.toArray();
System.out.println("Array from HashSet:");
for (Object obj : arrayFromHashSet) {
System.out.println(obj);
}
// Clearing the HashSet
myHashSet.clear();
System.out.println("HashSet after clear(): " + myHashSet);
}
}
package test;import java.util.HashSet;
import java.util.Iterator;
import java.util.Spliterator;
public class app {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> myHashSet = new HashSet<>();
// Adding elements
myHashSet.add("Apple");
myHashSet.add("Banana");
myHashSet.add("Orange");
myHashSet.add("Grapes");
// Displaying the HashSet
System.out.println("HashSet: " + myHashSet);
// Size of the HashSet
System.out.println("Size of HashSet: " + myHashSet.size());
// Checking for element existence
System.out.println("Contains 'Apple': " + myHashSet.contains("Apple"));
System.out.println("Contains 'Mango': " + myHashSet.contains("Mango"));
// Removing an element
myHashSet.remove("Orange");
System.out.println("HashSet after removing 'Orange': " + myHashSet);
// Iterating through the HashSet using Iterator
Iterator<String> iterator = myHashSet.iterator();
System.out.println("Elements using Iterator:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using SplitIterator (Not a typical use-case for HashSet, shown for reference)
Spliterator<String> spliterator = myHashSet.spliterator();
System.out.println("Elements using Spliterator:");
spliterator.forEachRemaining(System.out::println);
// Clone the HashSet
HashSet<String> clonedHashSet = (HashSet<String>) myHashSet.clone();
System.out.println("Cloned HashSet: " + clonedHashSet);
// Convert HashSet to array
Object[] arrayFromHashSet = myHashSet.toArray();
System.out.println("Array from HashSet:");
for (Object obj : arrayFromHashSet) {
System.out.println(obj);
}
// Clearing the HashSet
myHashSet.clear();
System.out.println("HashSet after clear(): " + myHashSet);
}
}
Program for LinkedHashSet
import java.util.Iterator;
import java.util.LinkedHashSet;
public class app {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
// Adding elements
linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Orange");
linkedHashSet.add("Grapes");
// Displaying the LinkedHashSet
System.out.println("LinkedHashSet: " + linkedHashSet);
// Size of the LinkedHashSet
System.out.println("Size: " + linkedHashSet.size());
// Iterating through the LinkedHashSet using Iterator
System.out.println("Elements using Iterator:");
Iterator<String> iterator = linkedHashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Checking if an element exists
System.out.println("Contains 'Orange'? " +
linkedHashSet.contains("Orange"));
// Removing an element
linkedHashSet.remove("Banana");
// Clearing the LinkedHashSet
linkedHashSet.clear();
// Checking if the set is empty after clearing
System.out.println("Is LinkedHashSet empty? " +
linkedHashSet.isEmpty());
}
}
Program for TreeHashSet
import java.util.TreeSet;
import java.util.Iterator;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
// Adding elements
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Grapes");
// Displaying the TreeSet
System.out.println("TreeSet: " + treeSet);
// Size of the TreeSet
System.out.println("Size: " + treeSet.size());
// Iterating through the TreeSet using Iterator
System.out.println("Elements using Iterator:");
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Checking if an element exists
System.out.println("Contains 'Orange'? " + treeSet.contains("Orange"));
// Removing an element
treeSet.remove("Banana");
// Clearing the TreeSet
treeSet.clear();
// Checking if the set is empty after clearing
System.out.println("Is TreeSet empty? " + treeSet.isEmpty());
}
}
Program for HashMap
import java.util.*;
public class app {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "shekar");
map.put(2, "raja");
map.put(3, "eddandi");
map.put(1, "sheki");
System.out.println(map);
Set<Integer> keys=map.keySet();
for (Integer integer : keys) {
System.out.println("key is : "+integer);
}
for (Integer integer : keys) {
System.out.println("key is +: "+integer+" value is :
"+map.get(integer));
}
Collection<String> s= map.values();
System.out.println(s);
}
}
Second program for HAshMap
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> hashMap = new HashMap<>();
// Adding key-value pairs
hashMap.put("Alice", 25);
hashMap.put("Bob", 30);
hashMap.put("Charlie", 28);
hashMap.put("David", 35);
// Accessing elements
System.out.println("Age of Alice: " + hashMap.get("Alice"));
// Iterating through the HashMap
System.out.println("\nIterating through the HashMap:");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
// Checking if a key exists
String searchKey = "Bob";
if (hashMap.containsKey(searchKey)) {
System.out.println("\n" + searchKey + " is present. Age: " +
hashMap.get(searchKey));
} else {
System.out.println("\n" + searchKey + " is not present in the HashMap.");
}
// Removing a key-value pair
hashMap.remove("Charlie");
System.out.println("\nAfter removing Charlie:");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
// Clearing the HashMap
hashMap.clear();
System.out.println("\nHashMap has been cleared. Size: " + hashMap.size());
}
}
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 = hashMap.keySet();
2. **`forEach()` Method with `keySet()`:**
- You can iterate over the keys using `forEach` and `keySet()`.
Example:
hashMap.keySet().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 = hashMap.values();
2. **`forEach()` Method with `values()`:**
- You can iterate over the values using `forEach` and `values()`.
- Example:
hashMap.values().forEach(value -> {
// Access each value
});
3. **`entrySet()` Method:**
- `entrySet()` returns a `Set` of `Map.Entry` objects containing both keys and
values.
- Example:
Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
String key = entry.getKey();
Integer value = entry.getValue();
// 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 java.util.Objects;
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 = s.clone();
System.out.println(s.equals(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 Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
shekar other = (shekar) obj;
return a == other.a && Objects.equals(b, other.b);
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
Program using toString() by overriding toString()
package test;
import java.util.Objects;
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);
System.out.println(p);
System.out.println(p.toString());
}
@Override
public String toString() {
return "app [a=" + a + ", b=" + b + "]";
}