0% found this document useful (0 votes)
91 views

Public Class Public Static Void: Main Args Coins

The document provides examples of how to use various methods from the Collections class in Java to work with and manipulate collections, including comparing collection elements, making collections read-only, shuffling elements, iterating through maps and tables, finding sublists, getting sublist from ArrayList, checking for duplicate values, and searching collections. It also includes examples of using Collections to create empty collections, get enumerations, and search collections using binary search with comparators.

Uploaded by

Deepak Bisht
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Public Class Public Static Void: Main Args Coins

The document provides examples of how to use various methods from the Collections class in Java to work with and manipulate collections, including comparing collection elements, making collections read-only, shuffling elements, iterating through maps and tables, finding sublists, getting sublist from ArrayList, checking for duplicate values, and searching collections. It also includes examples of using Collections to create empty collections, get enumerations, and search collections using binary search with comparators.

Uploaded by

Deepak Bisht
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

How to compare elements in a collection ?

Following example compares the element of a collection by converting a string into a treeset using Collection.min() and
Collection.max() methods of Collection class.

Eg-

public class MainClass {

public static void main(String[] args) {

String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };

Set set = new TreeSet();

for (int i = 0; i < coins.length; i++)set.add(coins[i]);

System.out.println(Collections.min(set));

System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));

for(int i = 0; i <= 10; i++)System.out.print('-');

System.out.println(Collections.max(set));

System.out.println(Collections.max(set,

String.CASE_INSENSITIVE_ORDER));

How to make a collection read-only ?

Following example shows how to make a collection read-only by using Collections.unmodifiableList() method of Collection class.

public class Main {

public static void main(String[] argv) throws Exception {

List stuff = Arrays.asList(new String[] { "a", "b" });

List list = new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

list.set(0, "new value");

} catch (UnsupportedOperationException e) {

Set set = new HashSet(stuff);

set = Collections.unmodifiableSet(set);
Map map = new HashMap();

map = Collections.unmodifiableMap(map);

System.out.println("Collection is read-only now.");

How to shuffle the elements of a collection ?

Collections.shuffle() method of Collections class.

How to iterate through elements of HashMap ?

Collection cl = hMap.values();

How to use enumeration to display contents of HashTable ?

Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the
HashTable.

public class Main {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

ht.put("1", "One");

ht.put("2", "Two");

ht.put("3", "Three");

Enumeration e = ht.elements();

while(e.hasMoreElements()) {

System.out.println(e.nextElement());

How to set view of Keys from Java Hashtable ?


Following example uses keys() method to get Enumeration of Keys of the Hashtable.

public class Main {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

ht.put("1", "One");

ht.put("2", "Two");

ht.put("3", "Three");

Enumeration e = ht.keys();

while (e.hasMoreElements()) {

System.out.println(e.nextElement());

} }

How to find a sublist in a List ?

Following example uses indexOfSubList() & lastIndexOfSubList() to check whether the sublist is there in the list or not & to find the
last occurance of the sublist in the list.

How to get sub list from ArrayList?


List<String> list = arrl.subList(2, 4);

How to find does ArrayList contains all list elements or not?


arrl.containsAll(list)

How to delete all elements from my ArrayList?


arrl.clear();

How to add all elements of a list to ArrayList?


arrl.addAll(list);

How to copy or clone a ArrayList?


arrl.clone();

How to copy vector to array?


vct.copyInto(copyArr);

How to find user defined objects as a key from LinkedHashMap?


hm.containsKey(key)

How to sort keys in TreeMap by using Comparator with user define objects?

class MyNameComp implements Comparator<Empl>{

@Override

public int compare(Empl e1, Empl e2) {

return e1.getName().compareTo(e2.getName());

} }
class MySalaryComp implements Comparator<Empl>{

@Override

public int compare(Empl e1, Empl e2) {

if(e1.getSalary() > e2.getSalary()){

return 1;

} else {

return -1;

} } }

How to reverse sorted keys in a TreeMap?


hm.descendingMap();

Write a program to find duplicate value from an array.

public static void main(String a[]){


String[] strArr = {"one","two","three","four","four","five"};
TreeSet<String> unique = new TreeSet<String>();
for(String str:strArr){
if(!unique.add(str)){
System.out.println("Duplicate Entry is: "+str);
}
}
How to avoid duplicate user defined objects in TreeSet?

To avoid duplicate user defined objects in TreeSet, you have to implement Comparator interface with equality verification. Below example gives a
sample code to implement it.
How to eliminate duplicate user defined objects from HashSet?

Below example shows how to avoid duplicate user defined objects from HashSet. You can achieve this by implementing equals and hashcode
methods at the user defined objects.
Hashtable implementation with equals and hashcode example.

Below example shows how to use user defined objects as keys. To avoid duplicates keys you have to implement equals and hashcode methods. In
below example we are using Emp object as key, and it has implemented equals, and hashcode methods. Example also enters duplicate object as key,
and you can see that Hashtable eleminates the duplicate keys.
public class MyHashtableUserKeys {

public static void main(String a[]){

Hashtable<Emp,String> tm = new Hashtable<Emp, String>();

tm.put(new Emp(134,"Ram",3000), "RAM");

tm.put(new Emp(235,"John",6000), "JOHN");

tm.put(new Emp(876,"Crish",2000), "CRISH");

tm.put(new Emp(512,"Tom",2400), "TOM");


System.out.println("Fecthing value by creating new key:");

Emp e = new Emp(512,"Tom",2400);

System.out.println(e+" ==> "+tm.get(e));

} }

class Emp{

private String name; private int salary; private int id;

public Emp(int id, String n, int s){ this.id = id; this.name = n; this.salary = s; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getSalary() { return salary; }

public void setSalary(int salary) { this.salary = salary; }

public String toString(){ return "Id: "+this.id+" -- Name: "+this.name+" -- Salary: "+this.salary; }

public void setId(int id) { this.id = id; }

public int getId() { return id; }

@Override

public int hashCode() {

System.out.println("In hashcode");

return this.getId(); }

@Override

public boolean equals(Object obj) {

Emp e = null;

if(obj instanceof Emp){

e = (Emp) obj; }

System.out.println("In equals");

if(this.getId() == e.getId()){

return true;

} else {

return false;

} } }

Output:
In hashcode
In hashcode
In hashcode
In hashcode
Fecthing value by creating new key:
In hashcode
In equals
Id: 512 -- Name: Tom -- Salary: 2400 ==> TOM

How to search user defined object from a List by using binary search using comparator?

The Collections.binarySearch() method searches the specified list for the specified user defined object using the binary search algorithm. The list
must be sorted into ascending order according to the specified comparator (as by the sort(List, Comparator) method), prior to making this call. If it is
not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be
found
Emp searchKey = new Emp(201,"John",40000);
int index = Collections.binarySearch(empList, searchKey, new EmpComp());
System.out.println("Index of the searched key: "+index);
}
}
class EmpComp implements Comparator<Emp>{

public int compare(Emp e1, Emp e2) {


if(e1.getEmpId() == e2.getEmpId()){
return 0;
} else {
return -1;
}
}
}
Write an example for Collections.checkedCollection() method.

Collections.checkedCollection() method returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the
wrong type will result in an immediate ClassCastException. Assuming a collection contains no incorrectly typed elements prior to the time a
dynamically typesafe view is generated, and that all subsequent access to the collection takes place through the view, it is guaranteed that the
collection cannot contain an incorrectly typed element.
Write an example for Collections.checkedList() method.

Collections.checkedList() method returns a dynamically typesafe view of the specified list. Any attempt to insert an element of the wrong type will
result in an immediate ClassCastException. Assuming a list contains no incorrectly typed elements prior to the time a dynamically typesafe view is
generated, and that all subsequent access to the list takes place through the view, it is guaranteed that the list cannot contain an incorrectly typed
element.
List chkList = Collections.checkedList(myList, String.class);
System.out.println("Checked list content: "+chkList);
//you can add any type of elements to myList object
myList.add(10);
//you cannot add any type of elements to chkList object, doing so
//throws ClassCastException
How to create empty list using Collections class?

Collections.emptyList() method returns the empty list (immutable). This list is serializable.
How to create empty set using Collections class?

Collections.emptySet() method returns the empty set (immutable). This set is serializable.
How to create empty map using Collections class?

Collections.emptyMap() method returns the empty map (immutable). This map is serializable.
How to Enumeration for ArrayList object?

Below example shows how to get enumeration object for ArrayList object. Collections.enumeration() method provides enumeration object.
How to convert Enumeration to List object?

Collections.list() method returns an array list containing the elements returned by the specified enumeration in the order they are returned by the
enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.
Enumeration<String> enm = vct.elements();
List<String> ll = Collections.list(enm);

How to fill or replace elements of a List or ArrayList?

Collections.fill() method replaces all of the elements of the specified list with the specified element. This method runs in linear time. You can find the
example code below:
Collections.fill(ll, "TEMP_STRING");

How to remove a particular character from a string ?

removeCharAt(str, 3))

How to reverse a String?

String reverse = new StringBuffer(string).reverse().toString();

How to search a word inside a string ?

int intIndex = strOrig.indexOf("Hello");

How to match regions in strings ?

String first_str = "Welcome to Microsoft";

String second_str = "I work with Microsoft";

boolean match = first_str.regionMatches(11, second_str, 12, 9);

How to determine the Unicode code point in string ?

String test_string = "Welcome to TutorialsPoint";

test_string.codePointBefore(5));
How to determine the upper bound of a two dimensional array ?

String[][] data = new String[2][5];

System.out.println("Dimension 1: " + data.length);//2

System.out.println("Dimension 2: " + data[0].length);//5

How to search the minimum and the maximum element in an array ?

This example shows how to search the minimum and maximum element in an array by using Collection.max() and
Collection.min() methods of Collection class int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

How to merge two arrays ?

This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class
and Arrays.toString () method of Array class.

List list = new ArrayList(Arrays.asList(a));

list.addAll(Arrays.asList(b));

Object[] c = list.toArray();

How to fill (initialize at once) an array ?

This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and
Array.fill(arrayname, starting index, ending index, value) method of Java Util class.

int array[] = new int[6];

Arrays.fill(array, 100);/100 100 100 100 100 100

Arrays.fill(array, 3, 6, 50); //100 100 100 50 50 50

How to extend an array after initialisation?

System.arraycopy(firstarray, 0, secondarray, 0, firstarray.length);

How to check if two arrays are equal or not?

Arrays.equals(ary, ary1)

How to use enum constructor, instance variable & method?

This example initializes enum using a costructor & getPrice() method & display values of enums.

enum Car {

lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;

Car(int p) { price = p; }

int getPrice() { return price; } }

public class Main {

public static void main(String args[]){

System.out.println("All car prices:");

for (Car c : Car.values()) System.out.println(

c + " costs " + c.getPrice() + " thousand dollars.");

}}

How to make a method take variable lentgth argument as an input?

static int sumvarargs(int... intArrays) {

Tower of Hanoi.

static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)


{
if (n == 1)
{
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
Sum of arithmetic series

= ((n / 2) * (2 * a + (n - 1) * d))

Program for EMI Calculator

Formula:
E = (P.r.(1+r)n) / ((1+r)n – 1)
Here,
P = loan amount i.e principal amount
R = Interest rate per month
T = Loan time period in year

calculate value of nCr

nCr = (n!) / (r! * (n-r)!)


matrix in spiral form

static void spiralPrint(int m, int n, int a[][])


{
int i, k = 0, c = 0;
/* k - starting row index
m - ending row index
c - starting column index
n - ending column index
i - iterator
*/
while (k < m && c < n)
{
// Print the first row from the remaining rows
for (i =c; i < n; ++i)
{
System.out.print(a[k][i]+" ");
}
k++;

// Print the last column from the remaining columns


for (i = k; i < m; ++i)
{
System.out.print(a[i][n-1]+" ");
}
n--;

// Print the last row from the remaining rows */


if ( k < m)
{
for (i = n-1; i >= l; --i)
{
System.out.print(a[m-1][i]+" ");
}
m--;
}

// Print the first column from the remaining columns */


if (c < n)
{
for (i = m-1; i >= k; --i)
{
System.out.print(a[i][c]+" ");
}
c++;
}
}
}

Single Linked list

class LinkedList
{
Node head; // head of list

/* Linked list Node*/


class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
//code

Insert

/* Inserts a new Node at front of the list. */


public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */


new_node.next = head;

/* 4. Move the head to point to new Node */


head = new_node;
}

/* Inserts a new node after the given prev_node. */


public void insertAfter(Node prev_node, int new_data)
{
/* 1. Check if the given Node is null */
if (prev_node == null)
{
System.out.println("The given previous node cannot be null");
return;
}

/* 2 & 3: Allocate the Node &


Put in the data*/
Node new_node = new Node(new_data);

/* 4. Make next of new Node as next of prev_node */


new_node.next = prev_node.next;

/* 5. make next of prev_node as new_node */


prev_node.next = new_node;
}

/* Appends a new node at the end. This method is


defined inside LinkedList class shown above */
public void append(int new_data)
{
/* 1. Allocate the Node &
2. Put in the data
3. Set next as null */
Node new_node = new Node(new_data);

/* 4. If the Linked List is empty, then make the


new node as head */
if (head == null)
{
head = new Node(new_data);
return;
}

/* 4. This new node is going to be the last node, so


make next of it as null */
new_node.next = null;

/* 5. Else traverse till the last node */


Node last = head;
while (last.next != null)
last = last.next;

/* 6. Change the next of last node */


last.next = new_node;
return;
}

Delete

/* Given a key, deletes the first occurrence of key in linked list */


void deleteNode(int key)
{
// Store head node
Node temp = head, prev = null;

// If head node itself holds the key to be deleted


if (temp != null && temp.data == key)
{
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key)
{
prev = temp;
temp = temp.next;
}

// If key was not present in linked list


if (temp == null) return;

// Unlink the node from linked list


prev.next = temp.next;
temp.next=null;
}

Write a function to delete a Linked List

Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to
access next of the current pointer if current pointer is deleted.
In Java, automatic garbage collection happens, so deleting a linked list is easy. We just need to change head to null.
/* Function deletes the entire linked list */
void deleteList()
{
head = null;
}
Recursive –find length
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int getCount(struct Node* head)
{
// Base case
if (head == NULL)
return 0;

// count is 1 + count of remaining list


return 1 + getCount(head->next);
}
middle of a given linked list

Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer
reaches end slow pointer will reach middle of the linked list.
/* Function to get the middle of the linked list*/
void printMiddle(struct Node *head)
{
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;

if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d]\n\n", slow_ptr->data);
}
}
n’th node from the end of a Linked List

Method 1 (Use length of linked list)


1) Calculate the length of Linked List. Let the length be len.
2) Print the (len – n + 1)th node from the begining of the Linked List.

Method 2 (Use two pointers)


Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First
move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches
end. Now main pointer will point to nth node from the end. Return main pointer.
/* Function to get the nth node from end of list */
void printNthFromLast(int n)
{
Node main_ptr = head;
Node ref_ptr = head;

int count = 0;
if (head != null)
{
while (count < n)
{
if (ref_ptr == null)
{
System.out.println(n+" is greater than the no "+
" of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
while (ref_ptr != null)
{
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no. "+n+" from last is "+
main_ptr.data);
}
}
Reverse a linked list

/* Function to reverse the linked list */


Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
Print reverse of a Linked List without actually reversing

void rev(struct node* head)

{
if(head == NULL)

return;

rev(head->next);

printf("%d ", head->data);

Segregate even and odd nodes in a Linked List

Method 1
The idea is to get pointer to the last node of list. And then traverse the list starting from the head node and move the
odd valued nodes from their current position to end of the list.

Write a function to get the intersection point of two Linked Lists.

Method 3(Using difference of node counts)


1) Get count of the nodes in the first list, let count be c1.
2) Get count of the nodes in the second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no
of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common
node is done by comparing the address of the nodes)

Detect loop in a linked list

Floyd’s Cycle-Finding Algorithm:


This is the fastest method. Traverse linked list using two pointers. Move one pointer by one and other pointer by
two. If these pointers meet at same node then there is a loop. If pointers do not meet then linked list doesn’t have
loop.

Find length of loop in linked list

First detect loop then stop fast pointer and count length btw slow and fast pointer

check if a singly linked list is palindrome

METHOD 1 (Use a Stack)


A simple solution is to use a stack of list nodes. This mainly involves three steps.
1) Traverse the given list from head to tail and push every visited node to stack.
2) Traverse the list again. For every visited node, pop a node from stack and compare data of popped node with
currently visited node.
3) If all nodes matched, then return true, else false.

METHOD 2 (By reversing the list)

1 First add all data in arryay or collection\


2 The reverse the list

3 Then again add ts data on ither array/ collection

4 Then compare two arrays/collection

METHOD 3 reverse printing

Remove duplicates from an unsorted linked list

METHOD 1 using collection


add all values to Hashset (unique element) then put all value to linked list

METHOD 2 (Using two loops)


This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and inner loop
compares the picked element with rest of the elements.

METHOD 3 (Use Sorting)

Sort then compare value to next node value and remove next node if value are same.

Merge two sorted linked lists such that merged list is in reverse order

1) Reverse first list ‘a’.


2) Reverse second list ‘b’.
3) Merge two reversed lists.

Reverse a Linked List in groups of given size | Set 1

Node *reverse (Node *head, int k)


{
Node* current = head;
Node* next = NULL;
Node* prev = NULL;
int count = 0;

/*reverse first k nodes of the linked list */


while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}

/* next is now a pointer to (k+1)th node


Recursively call for the list starting from current.
And make rest of the list as next of first node */
if (next != NULL)
head->next = reverse(next, k);

/* prev is new head of the input list */


return prev;
}
Input from user:

1.Scanner sc=new Scanner(System.in);


String input = sc.nextLine(); // get the entire line after the prompt
String[] strs = input.split(" ");

for (int i = 0; i < strs.length; i++) {


System.out.println((strs[i]));
}
sc.close();

2 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


String lines = br.readLine();

String[] strs = lines.trim().split("\\s+");

for (int i = 0; i < strs.length; i++) {


System.out.println((strs[i]));
}
Array input
3. Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int arr[]=new int[a];
int i;
String str=sc.next();
System.out.println(str);
for ( i=0;i<a;i++) {

arr[i]=sc.nextInt();
}
Level order:-

/* function to print level order traversal of tree*/


void printLevelOrder()
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
printGivenLevel(root, i);
}

/* Compute the "height" of a tree -- the number of


nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node root)
{
if (root == null)
return 0;
else
{
/* compute height of each subtree */
int lheight = height(root.left);
int rheight = height(root.right);

/* use the larger one */


if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}

/* Print nodes at the given level */


void printGivenLevel (Node root ,int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.data + " ");
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}

K Closest Points to the Origin

Consider two points with coordinates as (x1, y1) and (x2, y2) respectively.
The euclidean distance between these two points will be
√{(x2-x1)2 + (y2-y1)2}

Left view

/* Class to print the left view */


class BinaryTree
{
Node root;
static int max_level = 0;

// recursive function to print left view


void leftViewUtil(Node node, int level)
{
// Base Case
if (node==null) return;

// If this is the first node of its level


if (max_level < level)
{
System.out.print(" " + node.data);
max_level = level;
}

// Recur for left and right subtrees


leftViewUtil(node.left, level+1);
leftViewUtil(node.right, level+1);
}

// A wrapper over leftViewUtil()


void leftView()
{
leftViewUtil(root, 1);
}

/* testing for example nodes */


public static void main(String args[])
}
}

You might also like