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

Java Methods (1)

The document provides a comprehensive overview of various string manipulation methods in Java, including length, concatenation, comparison, and case conversion. It also covers StringBuilder and StringBuffer functionalities, showcasing methods like append, insert, delete, and reverse. Additionally, the document includes examples of array and collection operations, demonstrating methods such as sorting, searching, and filling arrays.

Uploaded by

bhanu
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)
9 views

Java Methods (1)

The document provides a comprehensive overview of various string manipulation methods in Java, including length, concatenation, comparison, and case conversion. It also covers StringBuilder and StringBuffer functionalities, showcasing methods like append, insert, delete, and reverse. Additionally, the document includes examples of array and collection operations, demonstrating methods such as sorting, searching, and filling arrays.

Uploaded by

bhanu
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
You are on page 1/ 85

Notes:

package StringAllMethods;

public class StringMethodsImpl {

public static void main(String args[]){

String str = "Hello World";


String str2 = "HELLO world";
String str3 = "apple,banana,orange";

// 1. length()
System.out.println("Length: " + str.length());

// 2. charAt()
System.out.println("Character at index 4: " + str.charAt(4));

// 3. concat()
String concatStr = str.concat(" - Java");
System.out.println("Concatenated String: " + concatStr);

// 4. equals()
System.out.println("Equals: " + str.equals("Hello World"));

// 5. equalsIgnoreCase()
System.out.println("Equals Ignore Case: " + str.equalsIgnoreCase(str2));

// 6. compareTo()
System.out.println("Compare To: " + str.compareTo("Hello Java"));

/*

The compareTo() method in Java is used to compare two strings lexicographically.


This method is a part of the Comparable interface, and it compares two strings based on the Unicode value of
each character in the strings.
returns 0 if equal.
if the first is greater, returns 1,
if the first is lesser, reurns -1 or difference b/w 1st two chars of 2 strings.

*/

// 7. compareToIgnoreCase()
System.out.println("Compare To Ignore Case: " + str.compareToIgnoreCase(str2));
// 8. substring()
System.out.println("Substring from index 6: " + str.substring(6));
System.out.println("Substring from 0 to 5: " + str.substring(0, 5));

// 9. indexOf()
System.out.println("Index of 'o': " + str.indexOf('o'));

// 10. lastIndexOf()
System.out.println("Last Index of 'o': " + str.lastIndexOf('o'));

// 11. contains()
System.out.println("Contains 'World': " + str.contains("World"));

// 12. replace()
System.out.println("Replace 'World' with 'Java': " + str.replace("World", "Java"));

// 13. replaceAll()
System.out.println("Replace all 'o' with 'x': " + str.replaceAll("o", "x"));

// 14. replaceFirst()
System.out.println("Replace first 'o' with 'x': " + str.replaceFirst("o", "x"));

// 15. toLowerCase()
System.out.println("Lower Case: " + str.toLowerCase());

// 16. toUpperCase()
System.out.println("Upper Case: " + str.toUpperCase());

// 17. trim()
String strWithSpaces = " Hello World ";
System.out.println("Trimmed: '" + strWithSpaces.trim() + "'");

// 18. split()
String[] fruits = str3.split(",");
System.out.println("Split (fruits): ");
for (String fruit : fruits) {
System.out.println(fruit);
}

// 19. isEmpty()
System.out.println("Is Empty: " + str.isEmpty());

// 20. startsWith()
System.out.println("Starts with 'Hello': " + str.startsWith("Hello"));
// 21. endsWith()
System.out.println("Ends with 'World': " + str.endsWith("World"));

// 22. valueOf()
int num = 100;
String numStr = String.valueOf(num);
System.out.println("Value of int: " + numStr);

// 23. hashCode()
System.out.println("Hash Code: " + str.hashCode());

// 24. matches()
System.out.println("Matches regex 'Hello.*': " + str.matches("Hello.*"));

// 25. intern()
String internedStr = str.intern();
System.out.println("Interned String: " + internedStr);

// 26. getBytes()
byte[] byteArray = str.getBytes();
System.out.println("Bytes of String:");
for (byte b : byteArray) {
System.out.print(b + " ");
}
System.out.println();

// 27. toCharArray()
char[] charArray = str.toCharArray();
System.out.println("To Char Array:");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println();

// 28. format()
String formattedStr = String.format("Welcome %s to the %s!", "John", "Java World");
System.out.println("Formatted String: " + formattedStr);

// 29. codePointAt()
System.out.println("Code point at index 0: " + str.codePointAt(0));

// 30. codePointBefore()
System.out.println("Code point before index 1: " + str.codePointBefore(1));

// 31. codePointCount()
System.out.println("Code point count from 0 to 5: " + str.codePointCount(0, 5));
// 32. regionMatches()
String anotherStr = "World of Java";
boolean regionMatches = str.regionMatches(6, anotherStr, 0, 5);
System.out.println("Region matches: " + regionMatches);
}
}

/*

1) Length: 11
2) Character at index 4: o
3) Concatenated String: Hello World - Java
4) Equals: true
5) Equals Ignore Case: true
6) Compare To: 1
7) Compare To Ignore Case: 0
8) Substring from index 6: World
Substring from 0 to 5: Hello
9) Index of 'o': 4
10) Last Index of 'o': 7
11) Contains 'World': true
12) Replace 'World' with 'Java': Hello Java
13) Replace all 'o' with 'x': Hellx Wxrld
14) Replace first 'o' with 'x': Hellx World
15) Lower Case: hello world
16) Upper Case: HELLO WORLD
17) Trimmed: 'Hello World'
18) Split (fruits):
apple
banana
orange
19) Is Empty: false
20) Starts with 'Hello': true
21) Ends with 'World': true
22) Value of int: 100
23) Hash Code: -862545276
24) Matches regex 'Hello.*': true
25) Interned String: Hello World
26) Bytes of String:
72 101 108 108 111 32 87 111 114 108 100
27) To Char Array:
Hello World
28) Formatted String: Welcome John to the Java World!
29) Code point at index 0: 72
30) Code point before index 1: 72
31) Code point count from 0 to 5: 5
32) Region matches: true

*/

package StringAllMethods;

public class StringBuilderBuffer {

public static void main(String[] args) {


// StringBuilder Example
StringBuilder sb = new StringBuilder("Hello");
System.out.println("Initial StringBuilder: " + sb);

// append()
sb.append(" World");
System.out.println("After append: " + sb);

// insert()
sb.insert(6, "Java ");
System.out.println("After insert: " + sb);

// delete()
sb.delete(6, 11);
System.out.println("After delete: " + sb);

// deleteCharAt()
sb.deleteCharAt(5);
System.out.println("After deleteCharAt: " + sb);

// replace()
sb.replace(6, 11, "Java");
System.out.println("After replace: " + sb);

// reverse()
sb.reverse();
System.out.println("After reverse: " + sb);
// substring()
String substring = sb.substring(6);
System.out.println("Substring from index 6: " + substring);

// charAt()
char charAtIndex = sb.charAt(6);
System.out.println("Character at index 6: " + charAtIndex);

// indexOf()
int indexOfJava = sb.indexOf("Java");
System.out.println("Index of 'Java': " + indexOfJava);

// lastIndexOf()
int lastIndexOfJava = sb.lastIndexOf("Java");
System.out.println("Last index of 'Java': " + lastIndexOfJava);

// length()
int length = sb.length();
System.out.println("Length of StringBuilder: " + length);

// capacity()
int capacity = sb.capacity();
System.out.println("Capacity of StringBuilder: " + capacity);

// ensureCapacity()
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity: " + sb.capacity());

// trimToSize()
sb.trimToSize();
System.out.println("Capacity after trimToSize: " + sb.capacity());

// toString()
String sbToString = sb.toString();
System.out.println("StringBuilder toString: " + sbToString);

// StringBuffer Example
StringBuffer sbf = new StringBuffer("Hello");
System.out.println("\nInitial StringBuffer: " + sbf);

// append()
sbf.append(" World");
System.out.println("After append: " + sbf);

// insert()
sbf.insert(6, "Java ");
System.out.println("After insert: " + sbf);

// delete()
sbf.delete(6, 11);
System.out.println("After delete: " + sbf);

// deleteCharAt()
sbf.deleteCharAt(5);
System.out.println("After deleteCharAt: " + sbf);

// replace()
sbf.replace(6, 11, "Java");
System.out.println("After replace: " + sbf);

// reverse()
sbf.reverse();
System.out.println("After reverse: " + sbf);

// substring()
String substringSbf = sbf.substring(6);
System.out.println("Substring from index 6: " + substringSbf);

// charAt()
char charAtIndexSbf = sbf.charAt(6);
System.out.println("Character at index 6: " + charAtIndexSbf);

// indexOf()
int indexOfJavaSbf = sbf.indexOf("Java");
System.out.println("Index of 'Java': " + indexOfJavaSbf);

// lastIndexOf()
int lastIndexOfJavaSbf = sbf.lastIndexOf("Java");
System.out.println("Last index of 'Java': " + lastIndexOfJavaSbf);

// length()
int lengthSbf = sbf.length();
System.out.println("Length of StringBuffer: " + lengthSbf);

// capacity()
int capacitySbf = sbf.capacity();
System.out.println("Capacity of StringBuffer: " + capacitySbf);

// ensureCapacity()
sbf.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity: " + sbf.capacity());
// trimToSize()
sbf.trimToSize();
System.out.println("Capacity after trimToSize: " + sbf.capacity());

// toString()
String sbfToString = sbf.toString();
System.out.println("StringBuffer toString: " + sbfToString);
}
}

/*

Initial StringBuilder: Hello


After append: Hello World
After insert: Hello Java World
After delete: Hello World
After deleteCharAt: HelloWorld
After replace: HelloJavaWorld
After reverse: dlroWavaJolleH
Substring from index 6: JavaWorld
Character at index 6: J
Index of 'Java': 6
Last index of 'Java': 6
Length of StringBuilder: 13
Capacity of StringBuilder: 22
Capacity after ensureCapacity: 50
Capacity after trimToSize: 13
StringBuilder toString: dlroWavaJolleH

Initial StringBuffer: Hello


After append: Hello World
After insert: Hello Java World
After delete: Hello World
After deleteCharAt: HelloWorld
After replace: HelloJavaWorld
After reverse: dlroWavaJolleH
Substring from index 6: JavaWorld
Character at index 6: J
Index of 'Java': 6
Last index of 'Java': 6
Length of StringBuffer: 13
Capacity of StringBuffer: 22
Capacity after ensureCapacity: 50
Capacity after trimToSize: 13
StringBuffer toString: dlroWavaJolleH

*/

import java.util.Arrays;

public class ArraysDemo {

public static void main(String[] args) {

// Initialize arrays for demonstration

int[] numbers = {5, 2, 9, 1, 5, 6};

int[] otherNumbers = {2, 5, 9, 1, 5, 6};

int[] filledArray = new int[5];

// 1. copyOf()

int[] copiedArray = Arrays.copyOf(numbers, numbers.length);

System.out.println("Copied Array: " + Arrays.toString(copiedArray));

// 2. copyOfRange()

int[] rangeCopiedArray = Arrays.copyOfRange(numbers, 1, 4);

System.out.println("Range Copied Array (1 to 4): " + Arrays.toString(rangeCopiedArray));

// 3. equals()

boolean areEqual = Arrays.equals(numbers, otherNumbers);

System.out.println("Arrays are equal: " + areEqual);


// 4. fill()

Arrays.fill(filledArray, 7);

System.out.println("Filled Array: " + Arrays.toString(filledArray));

// 5. hashCode()

int hashCode = Arrays.hashCode(numbers);

System.out.println("Hash Code of numbers array: " + hashCode);

// 6. parallelSort()

int[] parallelSortedArray = {5, 2, 9, 1, 5, 6};

Arrays.parallelSort(parallelSortedArray);

System.out.println("Parallel Sorted Array: " + Arrays.toString(parallelSortedArray));

// 7. sort()

int[] sortedArray = {5, 2, 9, 1, 5, 6};

Arrays.sort(sortedArray);

System.out.println("Sorted Array: " + Arrays.toString(sortedArray));

// 8. binarySearch()

int index = Arrays.binarySearch(sortedArray, 5);

System.out.println("Index of 5 in sortedArray: " + index);

// 9. toString()

String arrayString = Arrays.toString(numbers);

System.out.println("Array to String: " + arrayString);

// 10. asList() - Example with an array of strings


String[] stringArray = {"Java", "Python", "C++"};

System.out.println("List from array: " + Arrays.asList(stringArray));

// 11. spliterator() - Print elements using spliterator

System.out.println("Spliterator output: ");

Arrays.spliterator(numbers).forEachRemaining(System.out::print);

System.out.println();

// 12. stream() - Print elements using stream

System.out.println("Stream output: ");

Arrays.stream(numbers).forEach(System.out::print);

System.out.println();

Copied Array: [5, 2, 9, 1, 5, 6]

Range Copied Array (1 to 4): [2, 9, 1]

Arrays are equal: false

Filled Array: [7, 7, 7, 7, 7]

Hash Code of numbers array: 91787236

Parallel Sorted Array: [1, 2, 5, 5, 6, 9]

Sorted Array: [1, 2, 5, 5, 6, 9]

Index of 5 in sortedArray: 2

Array to String: [5, 2, 9, 1, 5, 6]

List from array: [Java, Python, C++]


Spliterator output: 529156

Stream output: 529156

import java.util.*;

import java.util.stream.Collectors;

public class CollectionsDemo {

public static void main(String[] args) {

// Initialize data for demonstration

List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 9, 1, 5, 6));

List<String> stringList = new ArrayList<>(Arrays.asList("Java", "Python", "C++"));

Set<String> stringSet = new HashSet<>(Arrays.asList("Java", "Python", "JavaScript"));

Map<String, Integer> map = new HashMap<>(Map.of("One", 1, "Two", 2));

// 1. addAll()

List<String> newList = new ArrayList<>();

Collections.addAll(newList, "Hello", "World");

System.out.println("New List after addAll: " + newList);

// 2. binarySearch()

Collections.sort(numbers); // Binary search requires a sorted list

int index = Collections.binarySearch(numbers, 5);


System.out.println("Index of 5 in sorted numbers: " + index);

// 3. checkedCollection(), checkedList(), checkedMap(), checkedSet()

List<String> checkedList = Collections.checkedList(new ArrayList<>(), String.class);

System.out.println("Checked List: " + checkedList);

// 4. clone() - Note: clone() is not in Collections class, it's a method from Object class

// Using an alternative for cloning

List<Integer> clonedList = new ArrayList<>(numbers);

System.out.println("Cloned List: " + clonedList);

// 5. disjoint()

boolean disjoint = Collections.disjoint(numbers, Arrays.asList(7, 8, 9));

System.out.println("Numbers and [7, 8, 9] are disjoint: " + disjoint);

// 6. emptyList(), emptyMap(), emptySet()

List<String> emptyList = Collections.emptyList();

Map<String, Integer> emptyMap = Collections.emptyMap();

Set<String> emptySet = Collections.emptySet();

System.out.println("Empty List: " + emptyList);

System.out.println("Empty Map: " + emptyMap);

System.out.println("Empty Set: " + emptySet);

// 7. enumeration()

Enumeration<Integer> enumeration = Collections.enumeration(numbers);

System.out.print("Enumeration: ");

while (enumeration.hasMoreElements()) {
System.out.print(enumeration.nextElement() + " ");

System.out.println();

// 8. fill()

Collections.fill(numbers, 0);

System.out.println("List after fill: " + numbers);

// 9. frequency()

int frequency = Collections.frequency(numbers, 0);

System.out.println("Frequency of 0: " + frequency);

// 10. nCopies()

List<String> nCopiesList = Collections.nCopies(3, "Java");

System.out.println("List with 3 copies of 'Java': " + nCopiesList);

// 11. reverse()

Collections.reverse(numbers);

System.out.println("Reversed List: " + numbers);

// 12. rotate()

Collections.rotate(numbers, 2);

System.out.println("List after rotation by 2 positions: " + numbers);

// 13. shuffle()

Collections.shuffle(numbers);

System.out.println("Shuffled List: " + numbers);


// 14. sort() and sort() with Comparator

Collections.sort(numbers);

System.out.println("Sorted List: " + numbers);

// 15. swap()

Collections.swap(numbers, 0, 1);

System.out.println("List after swapping first and second elements: " + numbers);

// 16. synchronizedCollection(), synchronizedList(), synchronizedMap(), synchronizedSet()

Collection<Integer> synchronizedCollection = Collections.synchronizedCollection(new ArrayList<>(numbers));

List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>(numbers));

Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>(map));

Set<String> synchronizedSet = Collections.synchronizedSet(new HashSet<>(stringSet));

System.out.println("Synchronized Collection: " + synchronizedCollection);

System.out.println("Synchronized List: " + synchronizedList);

System.out.println("Synchronized Map: " + synchronizedMap);

System.out.println("Synchronized Set: " + synchronizedSet);

// 17. unmodifiableCollection(), unmodifiableList(), unmodifiableMap(), unmodifiableSet()

Collection<String> unmodifiableCollection = Collections.unmodifiableCollection(stringSet);

List<String> unmodifiableList = Collections.unmodifiableList(stringList);

Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(new HashMap<>(map));

Set<String> unmodifiableSet = Collections.unmodifiableSet(stringSet);

System.out.println("Unmodifiable Collection: " + unmodifiableCollection);

System.out.println("Unmodifiable List: " + unmodifiableList);


System.out.println("Unmodifiable Map: " + unmodifiableMap);

System.out.println("Unmodifiable Set: " + unmodifiableSet);

// 18. max() and min()

List<Integer> maxMinList = Arrays.asList(1, 2, 3, 4, 5);

System.out.println("Max value: " + Collections.max(maxMinList));

System.out.println("Min value: " + Collections.min(maxMinList));

// 19. replaceAll()

List<String> replaceList = new ArrayList<>(Arrays.asList("a", "b", "a", "c"));

Collections.replaceAll(replaceList, "a", "z");

System.out.println("List after replaceAll: " + replaceList);

// 20. synchronizedCollection() - Example demonstrating synchronization

synchronizedCollection.forEach(System.out::println);

// 21. synchronizedList() - Example demonstrating synchronization

synchronizedList.forEach(System.out::println);

// 22. synchronizedMap() - Example demonstrating synchronization

synchronizedMap.forEach((k, v) -> System.out.println(k + "=" + v));

// 23. synchronizedSet() - Example demonstrating synchronization

synchronizedSet.forEach(System.out::println);

// 24. unmodifiableCollection() - Demonstrate attempting to modify an unmodifiable collection

try {
unmodifiableCollection.add("NewElement");

} catch (UnsupportedOperationException e) {

System.out.println("Cannot modify unmodifiable collection: " + e);

// 25. unmodifiableList() - Demonstrate attempting to modify an unmodifiable list

try {

unmodifiableList.add("NewElement");

} catch (UnsupportedOperationException e) {

System.out.println("Cannot modify unmodifiable list: " + e);

// 26. copy() - Copy elements from one list to another

List<Integer> dest = new ArrayList<>(Collections.nCopies(numbers.size(), 0));

Collections.copy(dest, numbers);

System.out.println("Destination list after copy: " + dest);

// 27. sort() with a custom comparator

List<String> customSortedList = new ArrayList<>(Arrays.asList("banana", "apple", "cherry"));

Collections.sort(customSortedList, Comparator.reverseOrder());

System.out.println("Custom sorted list in reverse order: " + customSortedList);

// 28. fill() on a different list

List<String> fillList = new ArrayList<>(Arrays.asList("x", "y", "z"));

Collections.fill(fillList, "filled");

System.out.println("List after fill with 'filled': " + fillList);


// 29. disjoint() with different data

List<Integer> list1 = Arrays.asList(1, 2, 3);

List<Integer> list2 = Arrays.asList(4, 5, 6);

boolean isDisjoint = Collections.disjoint(list1, list2);

System.out.println("List1 and List2 are disjoint: " + isDisjoint);

// 30. reverse() on another list

List<String> reverseList = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));

Collections.reverse(reverseList);

System.out.println("Reversed list: " + reverseList);

New List after addAll: [Hello, World]

Index of 5 in sorted numbers: 4

Checked List: []

Cloned List: [5, 2, 9, 1, 5, 6]

Numbers and [7, 8, 9] are disjoint: true

Empty List: []

Empty Map: {}

Empty Set: []

Enumeration: 5 2 9 1 5 6

List after fill: [0, 0, 0, 0, 0, 0]

Frequency of 0: 6

List with 3 copies of 'Java': [Java, Java, Java]


Reversed List: [0, 0, 0, 0, 0, 0]

List after rotation by 2 positions: [0, 0, 0, 0, 0, 0]

Shuffled List: [0, 0, 0, 0, 0, 0]

Sorted List: [0, 0, 0, 0, 0, 0]

List after swapping first and second elements: [0, 0, 0, 0, 0, 0]

Synchronized Collection: [0, 0, 0, 0, 0, 0]

Synchronized List: [0, 0, 0, 0, 0, 0]

Synchronized Map: {One=1, Two=2}

Synchronized Set: [Java, Python, JavaScript]

Unmodifiable Collection: [Java, Python, JavaScript]

Unmodifiable List: [Java, Python, C++]

Unmodifiable Map: {One=1, Two=2}

Unmodifiable Set: [Java, Python, JavaScript]

Max value: 5

Min value: 1

List after replaceAll: [z, b, z, c]

Synchronized Collection: 0

Synchronized Collection: 0

Synchronized Collection: 0

Synchronized Collection: 0

Synchronized Collection: 0

Synchronized Collection: 0

Synchronized List: 0

Synchronized List: 0

Synchronized List: 0

Synchronized List: 0

Synchronized List: 0
Synchronized List: 0

Synchronized Map: One=1

Synchronized Map: Two=2

Synchronized Set: JavaScript

Synchronized Set: Python

Synchronized Set: Java

Destination list after copy: [0, 0, 0, 0, 0, 0]

Custom sorted list in reverse order: [cherry, banana, apple]

List after fill with 'filled': [filled, filled, filled]

List1 and List2 are disjoint: true

Reversed list: [d, c, b, a]

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class CollectionMethodsExample {

public static void main(String[] args) {

// Create a collection

Collection<String> collection = new ArrayList<>();

// 1. add(E e)

collection.add("Apple");

collection.add("Banana");
collection.add("Cherry");

System.out.println("Collection after add: " + collection);

// 2. addAll(Collection<? extends E> c)

Collection<String> newFruits = new ArrayList<>();

newFruits.add("Date");

newFruits.add("Elderberry");

collection.addAll(newFruits);

System.out.println("Collection after addAll: " + collection);

// 3. clear()

collection.clear();

System.out.println("Collection after clear: " + collection);

// 4. contains(Object o)

collection.add("Fig");

System.out.println("Collection contains 'Fig': " + collection.contains("Fig"));

// 5. containsAll(Collection<?> c)

Collection<String> checkCollection = new ArrayList<>();

checkCollection.add("Fig");

System.out.println("Collection contains all elements of checkCollection: " + collection.containsAll(checkCollection));

// 6. isEmpty()

System.out.println("Collection is empty: " + collection.isEmpty());


// 7. iterator()

collection.add("Grape");

collection.add("Honeydew");

Iterator<String> iterator = collection.iterator();

System.out.print("Elements using iterator: ");

while (iterator.hasNext()) {

System.out.print(iterator.next() + " ");

System.out.println();

// 8. remove(Object o)

collection.remove("Grape");

System.out.println("Collection after remove 'Grape': " + collection);

// 9. removeAll(Collection<?> c)

Collection<String> removeCollection = new ArrayList<>();

removeCollection.add("Honeydew");

collection.removeAll(removeCollection);

System.out.println("Collection after removeAll removeCollection: " + collection);

// 10. retainAll(Collection<?> c)

Collection<String> retainCollection = new ArrayList<>();

retainCollection.add("Fig");

collection.retainAll(retainCollection);

System.out.println("Collection after retainAll retainCollection: " + collection);


// 11. size()

System.out.println("Size of the collection: " + collection.size());

// 12. toArray()

Object[] array = collection.toArray();

System.out.print("Collection toArray: ");

for (Object obj : array) {

System.out.print(obj + " ");

System.out.println();

// 13. toArray(T[] a)

String[] array2 = new String[collection.size()];

array2 = collection.toArray(array2);

System.out.print("Collection toArray(T[] a): ");

for (String str : array2) {

System.out.print(str + " ");

System.out.println();

Collection after add: [Apple, Banana, Cherry]

Collection after addAll: [Apple, Banana, Cherry, Date, Elderberry]

Collection after clear: []


Collection contains 'Fig': false

Collection contains all elements of checkCollection: false

Collection is empty: true

Elements using iterator: Grape Honeydew

Collection after remove 'Grape': [Honeydew]

Collection after removeAll removeCollection: []

Collection after retainAll retainCollection: [Fig]

Size of the collection: 1

Collection toArray: Fig

Collection toArray(T[] a): Fig

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

public class ListMethodsExample {

public static void main(String[] args) {

// Create a list

List<String> list = new ArrayList<>();

// 1. add(int index, E element)

list.add("Apple");
list.add("Banana");

list.add("Cherry");

list.add(1, "Blueberry"); // Insert at index 1

System.out.println("List after add(int index, E element): " + list);

// 2. addAll(int index, Collection<? extends E> c)

List<String> moreFruits = new ArrayList<>();

moreFruits.add("Date");

moreFruits.add("Elderberry");

list.addAll(2, moreFruits); // Insert at index 2

System.out.println("List after addAll(int index, Collection<? extends E> c): " + list);

// 3. get(int index)

String fruitAtIndex2 = list.get(2);

System.out.println("Element at index 2: " + fruitAtIndex2);

// 4. indexOf(Object o)

int indexOfCherry = list.indexOf("Cherry");

System.out.println("Index of 'Cherry': " + indexOfCherry);

// 5. lastIndexOf(Object o)

int lastIndexOfDate = list.lastIndexOf("Date");

System.out.println("Last index of 'Date': " + lastIndexOfDate);

// 6. listIterator()

ListIterator<String> listIterator = list.listIterator();

System.out.print("List elements using listIterator(): ");


while (listIterator.hasNext()) {

System.out.print(listIterator.next() + " ");

System.out.println();

// 7. listIterator(int index)

ListIterator<String> listIteratorAtIndex = list.listIterator(3);

System.out.print("List elements using listIterator(int index): ");

while (listIteratorAtIndex.hasNext()) {

System.out.print(listIteratorAtIndex.next() + " ");

System.out.println();

// 8. remove(int index)

list.remove(2); // Remove element at index 2

System.out.println("List after remove(int index): " + list);

// 9. set(int index, E element)

list.set(1, "Fig"); // Replace element at index 1

System.out.println("List after set(int index, E element): " + list);

// 10. subList(int fromIndex, int toIndex)

List<String> subList = list.subList(1, 3); // Get sublist from index 1 to 2 (toIndex is exclusive)

System.out.println("Sublist from index 1 to 3: " + subList);

}
List after add(int index, E element): [Apple, Blueberry, Banana, Cherry]

List after addAll(int index, Collection<? extends E> c): [Apple, Blueberry, Date, Elderberry, Banana, Cherry]

Element at index 2: Date

Index of 'Cherry': 5

Last index of 'Date': 2

List elements using listIterator(): Apple Blueberry Date Elderberry Banana Cherry

List elements using listIterator(int index): Date Elderberry Banana Cherry

List after remove(int index): [Apple, Blueberry, Elderberry, Banana, Cherry]

List after set(int index, E element): [Apple, Fig, Elderberry, Banana, Cherry]

Sublist from index 1 to 3: [Fig, Elderberry]

import java.util.HashSet;

import java.util.Set;

import java.util.Iterator;

public class SetMethodsExample {

public static void main(String[] args) {

// Create a set

Set<String> set = new HashSet<>();

// 1. add(E e)
set.add("Apple");

set.add("Banana");

set.add("Cherry");

System.out.println("Set after add: " + set);

// 2. addAll(Collection<? extends E> c)

Set<String> moreFruits = new HashSet<>();

moreFruits.add("Date");

moreFruits.add("Elderberry");

set.addAll(moreFruits);

System.out.println("Set after addAll: " + set);

// 3. clear()

set.clear();

System.out.println("Set after clear: " + set);

// 4. contains(Object o)

set.add("Fig");

System.out.println("Set contains 'Fig': " + set.contains("Fig"));

// 5. containsAll(Collection<?> c)

Set<String> checkSet = new HashSet<>();

checkSet.add("Fig");

System.out.println("Set contains all elements of checkSet: " + set.containsAll(checkSet));

// 6. isEmpty()

System.out.println("Set is empty: " + set.isEmpty());


// 7. iterator()

set.add("Grape");

set.add("Honeydew");

Iterator<String> iterator = set.iterator();

System.out.print("Elements using iterator: ");

while (iterator.hasNext()) {

System.out.print(iterator.next() + " ");

System.out.println();

// 8. remove(Object o)

set.remove("Grape");

System.out.println("Set after remove 'Grape': " + set);

// 9. removeAll(Collection<?> c)

Set<String> removeSet = new HashSet<>();

removeSet.add("Honeydew");

set.removeAll(removeSet);

System.out.println("Set after removeAll removeSet: " + set);

// 10. retainAll(Collection<?> c)

Set<String> retainSet = new HashSet<>();

retainSet.add("Fig");

set.retainAll(retainSet);

System.out.println("Set after retainAll retainSet: " + set);


// 11. size()

System.out.println("Size of the set: " + set.size());

// 12. toArray()

Object[] array = set.toArray();

System.out.print("Set toArray: ");

for (Object obj : array) {

System.out.print(obj + " ");

System.out.println();

// 13. toArray(T[] a)

String[] array2 = new String[set.size()];

array2 = set.toArray(array2);

System.out.print("Set toArray(T[] a): ");

for (String str : array2) {

System.out.print(str + " ");

System.out.println();

Set after add: [Apple, Banana, Cherry]

Set after addAll: [Apple, Banana, Cherry, Date, Elderberry]

Set after clear: []


Set contains 'Fig': false

Set contains all elements of checkSet: false

Set is empty: true

Elements using iterator: Grape Honeydew

Set after remove 'Grape': [Honeydew]

Set after removeAll removeSet: []

Set after retainAll retainSet: [Fig]

Size of the set: 1

Set toArray: Fig

Set toArray(T[] a): Fig

import java.util.LinkedList;

import java.util.Queue;

public class QueueMethodsExample {

public static void main(String[] args) {

// Create a queue

Queue<String> queue = new LinkedList<>();

// 1. add(E e)

queue.add("Apple");

queue.add("Banana");

queue.add("Cherry");

System.out.println("Queue after add: " + queue);


// 2. offer(E e)

queue.offer("Date");

queue.offer("Elderberry");

System.out.println("Queue after offer: " + queue);

// 3. remove()

String removedElement = queue.remove();

System.out.println("Element removed by remove(): " + removedElement);

System.out.println("Queue after remove: " + queue);

// 4. poll()

String polledElement = queue.poll();

System.out.println("Element removed by poll(): " + polledElement);

System.out.println("Queue after poll: " + queue);

// 5. peek()

String peekedElement = queue.peek();

System.out.println("Element at the head of the queue (peek()): " + peekedElement);

// 6. element()

String element = queue.element();

System.out.println("Element at the head of the queue (element()): " + element);

}
Queue after add: [Apple, Banana, Cherry]

Queue after offer: [Apple, Banana, Cherry, Date, Elderberry]

Element removed by remove(): Apple

Queue after remove: [Banana, Cherry, Date, Elderberry]

Element removed by poll(): Banana

Queue after poll: [Cherry, Date, Elderberry]

Element at the head of the queue (peek()): Cherry

Element at the head of the queue (element()): Cherry

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import java.util.Collection;

import java.util.function.BiFunction;

import java.util.function.Function;

public class MapMethodsExample {

public static void main(String[] args) {

// Create a map

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

// 1. put(K key, V value)


map.put("A", "Apple");

map.put("B", "Banana");

map.put("C", "Cherry");

System.out.println("Map after put: " + map);

// 2. putAll(Map<? extends K, ? extends V> m)

Map<String, String> additionalMap = new HashMap<>();

additionalMap.put("D", "Date");

additionalMap.put("E", "Elderberry");

map.putAll(additionalMap);

System.out.println("Map after putAll: " + map);

// 3. remove(Object key)

String removedValue = map.remove("B");

System.out.println("Value removed by remove(): " + removedValue);

System.out.println("Map after remove: " + map);

// 4. clear()

map.clear();

System.out.println("Map after clear: " + map);

// 5. containsKey(Object key)

map.put("F", "Fig");

System.out.println("Map contains key 'F': " + map.containsKey("F"));

// 6. containsValue(Object value)

System.out.println("Map contains value 'Fig': " + map.containsValue("Fig"));


// 7. get(Object key)

String value = map.get("F");

System.out.println("Value associated with key 'F': " + value);

// 8. isEmpty()

System.out.println("Map is empty: " + map.isEmpty());

// 9. keySet()

Set<String> keys = map.keySet();

System.out.println("Keys in the map: " + keys);

// 10. values()

Collection<String> values = map.values();

System.out.println("Values in the map: " + values);

// 11. entrySet()

Set<Map.Entry<String, String>> entries = map.entrySet();

System.out.println("Entries in the map: " + entries);

// 12. size()

System.out.println("Size of the map: " + map.size());

// 13. replace(K key, V value)

map.put("G", "Grape");

map.replace("G", "Green Grape");

System.out.println("Map after replace: " + map);


// 14. replace(K key, V oldValue, V newValue)

map.replace("G", "Green Grape", "Grape");

System.out.println("Map after replace with oldValue check: " + map);

// 15. computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

map.computeIfAbsent("H", key -> "Honeydew");

System.out.println("Map after computeIfAbsent: " + map);

// 16. computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

map.computeIfPresent("H", (key, value) -> value + " Melon");

System.out.println("Map after computeIfPresent: " + map);

// 17. compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

map.compute("H", (key, value) -> (value == null) ? "Mango" : value + " and Mango");

System.out.println("Map after compute: " + map);

// 18. merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

map.merge("H", "Mixed", (oldValue, newValue) -> oldValue + " " + newValue);

System.out.println("Map after merge: " + map);

Map after put: {A=Apple, B=Banana, C=Cherry}


Map after putAll: {A=Apple, B=Banana, C=Cherry, D=Date, E=Elderberry}

Value removed by remove(): Banana

Map after remove: {A=Apple, C=Cherry, D=Date, E=Elderberry}

Value associated with key 'F': null

Map is empty: false

Keys in the map: [A, C, D, E]

Values in the map: [Apple, Cherry, Date, Elderberry]

Entries in the map: [A=Apple, C=Cherry, D=Date, E=Elderberry]

Size of the map: 4

Map after replace: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Green Grape}

Map after replace with oldValue check: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Grape}

Map after computeIfAbsent: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Grape, H=Honeydew}

Map after computeIfPresent: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Grape, H=Honeydew Melon}

Map after compute: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Grape, H=Honeydew Melon and Mango}

Map after merge: {A=Apple, C=Cherry, D=Date, E=Elderberry, G=Grape, H=Honeydew Melon and Mango Mixed}

import java.util.*;

import java.util.function.Function;

import java.util.function.Predicate;

import java.util.stream.Collectors;

import java.util.stream.Stream;

public class CollectorsExample {


public static void main(String[] args) {

List<String> words = Arrays.asList("apple", "banana", "apricot", "blueberry", "avocado");

// 1. toList

List<String> list = words.stream().collect(Collectors.toList());

System.out.println("toList: " + list);

// 2. toSet

Set<String> set = words.stream().collect(Collectors.toSet());

System.out.println("toSet: " + set);

// 3. toMap

Map<Integer, String> map = words.stream().collect(Collectors.toMap(String::length, Function.identity()));

System.out.println("toMap: " + map);

// 4. joining

String joined = words.stream().collect(Collectors.joining());

System.out.println("joining: " + joined);

// 5. joining with delimiter

String joinedWithDelimiter = words.stream().collect(Collectors.joining(", "));

System.out.println("joining with delimiter: " + joinedWithDelimiter);

// 6. joining with delimiter, prefix, and suffix

String joinedWithPrefixSuffix = words.stream().collect(Collectors.joining(", ", "[", "]"));

System.out.println("joining with delimiter, prefix, and suffix: " + joinedWithPrefixSuffix);


// 7. groupingBy

Map<Character, List<String>> groupedByFirstLetter = words.stream()

.collect(Collectors.groupingBy(word -> word.charAt(0)));

System.out.println("groupingBy: " + groupedByFirstLetter);

// 8. groupingBy with downstream collector

Map<Character, Long> countByFirstLetter = words.stream()

.collect(Collectors.groupingBy(word -> word.charAt(0), Collectors.counting()));

System.out.println("groupingBy with counting: " + countByFirstLetter);

// 9. groupingBy with map factory

Map<Character, Set<String>> groupingByWithMapFactory = words.stream()

.collect(Collectors.groupingBy(

word -> word.charAt(0),

TreeMap::new,

Collectors.toSet()

));

System.out.println("groupingBy with map factory: " + groupingByWithMapFactory);

// 10. partitioningBy

Map<Boolean, List<String>> partitioned = words.stream()

.collect(Collectors.partitioningBy(word -> word.length() > 5));

System.out.println("partitioningBy: " + partitioned);

// 11. partitioningBy with downstream collector

Map<Boolean, Set<String>> partitionedWithSet = words.stream()

.collect(Collectors.partitioningBy(word -> word.length() > 5, Collectors.toSet()));


System.out.println("partitioningBy with Set: " + partitionedWithSet);

// 12. counting

long count = words.stream().collect(Collectors.counting());

System.out.println("counting: " + count);

// 13. summarizingInt

IntSummaryStatistics stats = words.stream().collect(Collectors.summarizingInt(String::length));

System.out.println("summarizingInt: " + stats);

// 14. summarizingLong

LongSummaryStatistics longStats = words.stream().mapToLong(String::length).collect(Collectors.summarizingLong());

System.out.println("summarizingLong: " + longStats);

// 15. summarizingDouble

DoubleSummaryStatistics doubleStats =
words.stream().mapToDouble(String::length).collect(Collectors.summarizingDouble());

System.out.println("summarizingDouble: " + doubleStats);

// 16. averagingInt

double averageLength = words.stream().collect(Collectors.averagingInt(String::length));

System.out.println("averagingInt: " + averageLength);

// 17. averagingLong

double averageLongLength = words.stream().mapToLong(String::length).collect(Collectors.averagingLong());

System.out.println("averagingLong: " + averageLongLength);


// 18. averagingDouble

double averageDoubleLength = words.stream().mapToDouble(String::length).collect(Collectors.averagingDouble());

System.out.println("averagingDouble: " + averageDoubleLength);

// 19. reducing

Optional<String> concatenated = words.stream().collect(Collectors.reducing((s1, s2) -> s1 + s2));

System.out.println("reducing: " + concatenated.orElse(""));

// 20. reducing with identity

String reducedWithIdentity = words.stream().collect(Collectors.reducing("Start: ", (s1, s2) -> s1 + s2)).orElse("");

System.out.println("reducing with identity: " + reducedWithIdentity);

// 21. reducing with mapping

String reducedWithMapping = words.stream().collect(Collectors.reducing("Start: ", String::toUpperCase, (s1, s2) -> s1 +


s2));

System.out.println("reducing with mapping: " + reducedWithMapping);

// 22. mapping

List<Integer> mappedLengths = words.stream()

.collect(Collectors.mapping(String::length, Collectors.toList()));

System.out.println("mapping: " + mappedLengths);

// 23. flatMapping

List<String> flatMapped = words.stream()

.collect(Collectors.flatMapping(word -> Stream.of(word.toUpperCase(), word.toLowerCase()), Collectors.toList()));

System.out.println("flatMapping: " + flatMapped);


// 24. collectingAndThen

List<String> collectedAndTransformed = words.stream()

.collect(Collectors.collectingAndThen(Collectors.toList(), list -> {

list.add("Extra");

return list;

}));

System.out.println("collectingAndThen: " + collectedAndTransformed);

// Additional methods for completeness

// 25. Collectors.toMap() with value transformer

Map<Integer, String> mapWithTransformer = words.stream()

.collect(Collectors.toMap(String::length, String::toUpperCase));

System.out.println("toMap with value transformer: " + mapWithTransformer);

// 26. Collectors.groupingBy() with downstream collector example

Map<Character, List<String>> groupedByFirstLetterList = words.stream()

.collect(Collectors.groupingBy(word -> word.charAt(0), Collectors.mapping(String::toUpperCase,


Collectors.toList())));

System.out.println("groupingBy with mapping and downstream collector: " + groupedByFirstLetterList);

// 27. Collectors.partitioningBy() with downstream collector example

Map<Boolean, List<String>> partitionedWithMapping = words.stream()

.collect(Collectors.partitioningBy(word -> word.length() > 5, Collectors.mapping(String::toUpperCase,


Collectors.toList())));

System.out.println("partitioningBy with mapping and downstream collector: " + partitionedWithMapping);

// 28. Collectors.flatMapping() with a transformer


List<String> flatMappedTransformed = words.stream()

.collect(Collectors.flatMapping(word -> Stream.of(word.toUpperCase(), word.toLowerCase()),


Collectors.mapping(String::trim, Collectors.toList())));

System.out.println("flatMapping with mapping: " + flatMappedTransformed);

// 29. Collectors.collectingAndThen() with a more complex transformation

List<String> collectingAndTransforming = words.stream()

.collect(Collectors.collectingAndThen(Collectors.toList(), list -> {

list.add("End");

return list.stream().map(String::toUpperCase).collect(Collectors.toList());

}));

System.out.println("collectingAndThen with complex transformation: " + collectingAndTransforming);

// 30. Combining Collectors

List<String> combinedCollectorsResult = words.stream()

.collect(Collectors.collectingAndThen(Collectors.toList(),

list -> list.stream().flatMap(word -> Stream.of(word, word.toUpperCase())).collect(Collectors.toList())));

System.out.println("combined collectors result: " + combinedCollectorsResult);

toList: [apple, banana, apricot, blueberry, avocado]

toSet: [banana, avocado, apricot, blueberry, apple]

toMap: {5=apple, 6=banana, 7=apricot, 9=blueberry, 7=avocado}

joining: applebananaapricotblueberryavocado
joining with delimiter: apple, banana, apricot, blueberry, avocado

joining with delimiter, prefix, and suffix: [apple, banana, apricot, blueberry, avocado]

groupingBy: {a=[apple, apricot, avocado], b=[banana, blueberry]}

groupingBy with counting: {a=3, b=2}

groupingBy with map factory: {a=[apple, apricot, avocado], b=[banana, blueberry]}

partitioningBy: {false=[apple, banana, apricot], true=[blueberry, avocado]}

partitioningBy with Set: {false=[apple, banana, apricot], true=[blueberry, avocado]}

counting: 5

summarizingInt: IntSummaryStatistics{count=5, sum=28, min=5, average=5.600000, max=9}

summarizingLong: LongSummaryStatistics{count=5, sum=28, min=5, average=5.600000, max=9}

summarizingDouble: DoubleSummaryStatistics{count=5, sum=28.0, min=5.0, average=5.6, max=9.0}

averagingInt: 5.6

averagingLong: 5.6

averagingDouble: 5.6

reducing: applebananaapricotblueberryavocado

reducing with identity: Start: applebananaapricotblueberryavocado

reducing with mapping: Start: APPLEBANANAPRICOOTBLUEBERRYAVOCADO

mapping: [5, 6, 7, 9, 7]

flatMapping: [APPLE, apple, BANANA, banana, APRICOT, apricot, BLUEBERRY, blueberry, AVOCADO, avocado]

collectingAndThen: [apple, banana, apricot, blueberry, avocado, Extra]

toMap with value transformer: {5=APPLE, 6=BANANA, 7=APRICOOT, 9=BLUEBERRY}

groupingBy with mapping and downstream collector: {a=[APPLE, APRICOT, AVOCADO], b=[BANANA, BLUEBERRY]}

partitioningBy with mapping and downstream collector: {false=[APPLE, BANANA, APRICOT], true=[BLUEBERRY,
AVOCADO]}

flatMapping with mapping: [APPLE, apple, BANANA, banana, APRICOT, apricot, BLUEBERRY, blueberry, AVOCADO,
avocado]

collectingAndThen with complex transformation: [APPLE, BANANA, APRICOT, BLUEBERRY, AVOCADO, END]
combined collectors result: [apple, APPLE, banana, BANANA, apricot, APRICOT, blueberry, BLUEBERRY, avocado,
AVOCADO]

import java.util.*;

import java.util.function.*;

import java.util.stream.*;

public class StreamMethodsExample {

public static void main(String[] args) {

List<String> words = Arrays.asList("apple", "banana", "apricot", "blueberry", "avocado");

// 1. forEach

System.out.print("forEach: ");

words.stream().forEach(word -> System.out.print(word + " "));

System.out.println();

// 2. forEachOrdered

System.out.print("forEachOrdered: ");

words.stream().unordered().forEachOrdered(word -> System.out.print(word + " "));

System.out.println();

// 3. iterator

Iterator<String> iterator = words.stream().iterator();


System.out.print("iterator: ");

while (iterator.hasNext()) {

System.out.print(iterator.next() + " ");

System.out.println();

// 4. spliterator

Spliterator<String> spliterator = words.stream().spliterator();

System.out.print("spliterator: ");

spliterator.forEachRemaining(System.out::print);

System.out.println();

// 5. close

try (Stream<String> stream = words.stream()) {

stream.forEach(System.out::print);

} catch (Exception e) {

e.printStackTrace();

System.out.println();

// 6. filter

List<String> filtered = words.stream().filter(word -> word.startsWith("a")).collect(Collectors.toList());

System.out.println("filter: " + filtered);

// 7. map

List<Integer> lengths = words.stream().map(String::length).collect(Collectors.toList());

System.out.println("map: " + lengths);


// 8. flatMap

List<String> flatMapped = words.stream().flatMap(word -> Stream.of(word,


word.toUpperCase())).collect(Collectors.toList());

System.out.println("flatMap: " + flatMapped);

// 9. distinct

List<String> distinct = words.stream().distinct().collect(Collectors.toList());

System.out.println("distinct: " + distinct);

// 10. sorted

List<String> sorted = words.stream().sorted().collect(Collectors.toList());

System.out.println("sorted: " + sorted);

// 11. peek

List<String> peeked = words.stream().peek(System.out::print).collect(Collectors.toList());

System.out.println("\npeek: " + peeked);

// 12. limit

List<String> limited = words.stream().limit(3).collect(Collectors.toList());

System.out.println("limit: " + limited);

// 13. skip

List<String> skipped = words.stream().skip(2).collect(Collectors.toList());

System.out.println("skip: " + skipped);

// 14. reduce
Optional<String> reduced = words.stream().reduce((s1, s2) -> s1 + s2);

System.out.println("reduce: " + reduced.orElse(""));

// 15. collect

List<String> collected = words.stream().collect(Collectors.toList());

System.out.println("collect: " + collected);

// 16. min

Optional<String> min = words.stream().min(Comparator.naturalOrder());

System.out.println("min: " + min.orElse(""));

// 17. max

Optional<String> max = words.stream().max(Comparator.naturalOrder());

System.out.println("max: " + max.orElse(""));

// 18. count

long count = words.stream().count();

System.out.println("count: " + count);

// 19. anyMatch

boolean anyMatch = words.stream().anyMatch(word -> word.startsWith("b"));

System.out.println("anyMatch: " + anyMatch);

// 20. allMatch

boolean allMatch = words.stream().allMatch(word -> word.length() > 3);

System.out.println("allMatch: " + allMatch);


// 21. noneMatch

boolean noneMatch = words.stream().noneMatch(word -> word.endsWith("z"));

System.out.println("noneMatch: " + noneMatch);

// 22. findFirst

Optional<String> findFirst = words.stream().findFirst();

System.out.println("findFirst: " + findFirst.orElse(""));

// 23. findAny

Optional<String> findAny = words.stream().findAny();

System.out.println("findAny: " + findAny.orElse(""));

// 24. toArray

String[] array = words.stream().toArray(String[]::new);

System.out.println("toArray: " + Arrays.toString(array));

// 25. boxed

List<Integer> boxed = IntStream.range(1, 4).boxed().collect(Collectors.toList());

System.out.println("boxed: " + boxed);

// 26. flatMapToInt

List<String> flatMappedToInt = words.stream().flatMapToInt(word ->


IntStream.of(word.length())).mapToObj(String::valueOf).collect(Collectors.toList());

System.out.println("flatMapToInt: " + flatMappedToInt);

// 27. flatMapToLong

List<String> flatMappedToLong = words.stream().flatMapToLong(word ->


LongStream.of(word.length())).mapToObj(String::valueOf).collect(Collectors.toList());
System.out.println("flatMapToLong: " + flatMappedToLong);

// 28. flatMapToDouble

List<String> flatMappedToDouble = words.stream().flatMapToDouble(word ->


DoubleStream.of(word.length())).mapToObj(String::valueOf).collect(Collectors.toList());

System.out.println("flatMapToDouble: " + flatMappedToDouble);

// 29. asDoubleStream

DoubleStream doubleStream = words.stream().mapToDouble(String::length).asDoubleStream();

System.out.println("asDoubleStream: " + doubleStream.boxed().collect(Collectors.toList()));

// 30. asLongStream

LongStream longStream = words.stream().mapToLong(String::length).asLongStream();

System.out.println("asLongStream: " + longStream.boxed().collect(Collectors.toList()));

// 31. asIntStream

IntStream intStream = words.stream().mapToInt(String::length).asIntStream();

System.out.println("asIntStream: " + intStream.boxed().collect(Collectors.toList()));

// 32. mapToInt

List<Integer> mapToInt = words.stream().mapToInt(String::length).boxed().collect(Collectors.toList());

System.out.println("mapToInt: " + mapToInt);

// 33. mapToLong

List<Long> mapToLong = words.stream().mapToLong(String::length).boxed().collect(Collectors.toList());

System.out.println("mapToLong: " + mapToLong);


// 34. mapToDouble

List<Double> mapToDouble = words.stream().mapToDouble(String::length).boxed().collect(Collectors.toList());

System.out.println("mapToDouble: " + mapToDouble);

// 35. summaryStatistics

IntSummaryStatistics stats = words.stream().mapToInt(String::length).summaryStatistics();

System.out.println("summaryStatistics: " + stats);

// 36. join

String joined = words.stream().collect(Collectors.joining(", ", "Start: ", " End"));

System.out.println("join: " + joined);

// 37. collectingAndThen

List<String> collectedAndTransformed = words.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {

list.add("Extra");

return list;

}));

System.out.println("collectingAndThen: " + collectedAndTransformed);

// 38. toList

List<String> toList = words.stream().collect(Collectors.toList());

System.out.println("toList: " + toList);

// 39. toSet

Set<String> toSet = words.stream().collect(Collectors.toSet());

System.out.println("toSet: " + toSet);


// 40. toMap

Map<Integer, String> toMap = words.stream().collect(Collectors.toMap(String::length, Function.identity()));

System.out.println("toMap: " + toMap);

forEach: apple banana apricot blueberry avocado

forEachOrdered: apple banana apricot blueberry avocado

iterator: apple banana apricot blueberry avocado

spliterator: applebananaapricotblueberryavocado

filter: [apple, apricot, avocado]

map: [5, 6, 7, 9, 7]

flatMap: [apple, APPLE, banana, BANANA, apricot, APRICOT, blueberry, BLUEBERRY, avocado, AVOCADO]

distinct: [apple, banana, apricot, blueberry, avocado]

sorted: [apple, apricot, avocado, banana, blueberry]

peek: applebananaapricotblueberryavocado

peek: [apple, banana, apricot, blueberry, avocado]

limit: [apple, banana, apricot]

skip: [apricot, blueberry, avocado]

reduce: applebananaapricotblueberryavocado

collect: [apple, banana, apricot, blueberry, avocado]

min: apple

max: blueberry

count: 5

anyMatch: true
allMatch: false

noneMatch: true

findFirst: apple

findAny: apple

toArray: [apple, banana, apricot, blueberry, avocado]

boxed: [1, 2, 3]

flatMapToInt: [5, 6, 7, 9, 7]

flatMapToLong: [5, 6, 7, 9, 7]

flatMapToDouble: [5.0, 6.0, 7.0, 9.0, 7.0]

asDoubleStream: [5.0, 6.0, 7.0, 9.0, 7.0]

asLongStream: [5, 6, 7, 9, 7]

asIntStream: [5, 6, 7, 9, 7]

mapToInt: [5, 6, 7, 9, 7]

mapToLong: [5, 6, 7, 9, 7]

mapToDouble: [5.0, 6.0, 7.0, 9.0, 7.0]

summaryStatistics: IntSummaryStatistics{count=5, sum=28, min=5, average=5.600000, max=9}

join: Start: apple, banana, apricot, blueberry, avocado End

collectingAndThen: [apple, banana, apricot, blueberry, avocado, Extra]

toList: [apple, banana, apricot, blueberry, avocado]

toSet: [apple, banana, apricot, blueberry, avocado]

toMap: {5=apple, 6=banana, 7=avocado, 9=blueberry}

import java.util.Optional;
import java.util.function.Consumer;

import java.util.function.Function;

import java.util.function.Predicate;

import java.util.function.Supplier;

public class OptionalMethodsExample {

public static void main(String[] args) {

// 1. empty

Optional<String> emptyOptional = Optional.empty();

System.out.println("empty: " + emptyOptional);

// 2. of

Optional<String> ofOptional = Optional.of("Hello");

System.out.println("of: " + ofOptional);

// 3. ofNullable

Optional<String> ofNullableOptional = Optional.ofNullable(null);

System.out.println("ofNullable (null): " + ofNullableOptional);

Optional<String> ofNullableOptionalWithValue = Optional.ofNullable("World");

System.out.println("ofNullable (value): " + ofNullableOptionalWithValue);

// 4. isPresent

System.out.println("isPresent (value): " + ofOptional.isPresent());

System.out.println("isPresent (null): " + ofNullableOptional.isPresent());

// 5. ifPresent

ofOptional.ifPresent(value -> System.out.println("ifPresent: " + value));


ofNullableOptional.ifPresent(value -> System.out.println("ifPresent (null)"));

// 6. ifPresentOrElse

ofOptional.ifPresentOrElse(

value -> System.out.println("ifPresentOrElse: " + value),

() -> System.out.println("ifPresentOrElse: value is absent")

);

ofNullableOptional.ifPresentOrElse(

value -> System.out.println("ifPresentOrElse (null)"),

() -> System.out.println("ifPresentOrElse: value is absent")

);

// 7. orElse

String orElseValue = ofNullableOptional.orElse("Default Value");

System.out.println("orElse: " + orElseValue);

// 8. orElseGet

String orElseGetValue = ofNullableOptional.orElseGet(() -> "Generated Default Value");

System.out.println("orElseGet: " + orElseGetValue);

// 9. orElseThrow

try {

String orElseThrowValue = ofNullableOptional.orElseThrow(() -> new RuntimeException("Value not present"));

System.out.println("orElseThrow: " + orElseThrowValue);

} catch (Exception e) {

System.out.println("orElseThrow: " + e.getMessage());

}
// 10. map

Optional<Integer> mapOptional = ofOptional.map(String::length);

System.out.println("map: " + mapOptional);

// 11. flatMap

Optional<String> flatMapOptional = ofOptional.flatMap(value -> Optional.of(value.toUpperCase()));

System.out.println("flatMap: " + flatMapOptional);

// 12. filter

Optional<String> filterOptional = ofOptional.filter(value -> value.startsWith("H"));

System.out.println("filter: " + filterOptional);

Optional<String> filterOptionalAbsent = ofOptional.filter(value -> value.startsWith("X"));

System.out.println("filter (absent): " + filterOptionalAbsent);

// 13. or

Optional<String> orOptional = ofNullableOptional.or(() -> Optional.of("Alternative Value"));

System.out.println("or: " + orOptional);

// 14. toString

System.out.println("toString (value): " + ofOptional.toString());

System.out.println("toString (null): " + ofNullableOptional.toString());

// 15. equals

Optional<String> anotherOfOptional = Optional.of("Hello");

System.out.println("equals: " + ofOptional.equals(anotherOfOptional));


// 16. hashCode

System.out.println("hashCode: " + ofOptional.hashCode());

// 17. get

try {

String getValue = ofOptional.get();

System.out.println("get (value): " + getValue);

} catch (Exception e) {

System.out.println("get (value): " + e.getMessage());

try {

String getValueAbsent = ofNullableOptional.get();

System.out.println("get (null): " + getValueAbsent);

} catch (Exception e) {

System.out.println("get (null): " + e.getMessage());

empty: Optional.empty

of: Optional[Hello]

ofNullable (null): Optional.empty


ofNullable (value): Optional[World]

isPresent (value): true

isPresent (null): false

ifPresent: Hello

ifPresent (null)

ifPresentOrElse: Hello

ifPresentOrElse: value is absent

orElse: Default Value

orElseGet: Generated Default Value

orElseThrow: Value not present

map: Optional[5]

flatMap: Optional[HELLO]

filter: Optional[Hello]

filter (absent): Optional.empty

or: Optional[Alternative Value]

toString (value): Optional[Hello]

toString (null): Optional.empty

equals: true

hashCode: 67369324

get (value): Hello

get (null): No value present

import java.util.function.*;
public class FunctionalInterfacesExample {

public static void main(String[] args) {

// Consumer<T>

Consumer<String> consumer = s -> System.out.println("Consumer: " + s);

consumer.accept("Hello, Consumer!");

// Function<T, R>

Function<Integer, String> function = i -> "Number: " + i;

System.out.println("Function: " + function.apply(10));

// Supplier<T>

Supplier<String> supplier = () -> "Hello, Supplier!";

System.out.println("Supplier: " + supplier.get());

// Predicate<T>

Predicate<String> predicate = s -> s.length() > 5;

System.out.println("Predicate: " + predicate.test("Hello, World!"));

// UnaryOperator<T> (extends Function<T, T>)

UnaryOperator<Integer> unaryOperator = i -> i * 2;

System.out.println("UnaryOperator: " + unaryOperator.apply(5));

// BinaryOperator<T> (extends BiFunction<T, T, T>)

BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;

System.out.println("BinaryOperator: " + binaryOperator.apply(3, 4));


// BiConsumer<T, U>

BiConsumer<String, Integer> biConsumer = (s, i) -> System.out.println("BiConsumer: " + s + ", " + i);

biConsumer.accept("Age", 30);

// BiFunction<T, U, R>

BiFunction<String, Integer, String> biFunction = (s, i) -> s + " is " + i + " years old";

System.out.println("BiFunction: " + biFunction.apply("John", 25));

// ObjIntConsumer<T>

ObjIntConsumer<String> objIntConsumer = (s, i) -> System.out.println("ObjIntConsumer: " + s + ", " + i);

objIntConsumer.accept("Score", 95);

// ObjLongConsumer<T>

ObjLongConsumer<String> objLongConsumer = (s, l) -> System.out.println("ObjLongConsumer: " + s + ", " + l);

objLongConsumer.accept("ID", 123456789L);

// ObjDoubleConsumer<T>

ObjDoubleConsumer<String> objDoubleConsumer = (s, d) -> System.out.println("ObjDoubleConsumer: " + s + ", " + d);

objDoubleConsumer.accept("Value", 9.99);

// IntConsumer

IntConsumer intConsumer = i -> System.out.println("IntConsumer: " + i);

intConsumer.accept(42);

// LongConsumer

LongConsumer longConsumer = l -> System.out.println("LongConsumer: " + l);

longConsumer.accept(123456789L);
// DoubleConsumer

DoubleConsumer doubleConsumer = d -> System.out.println("DoubleConsumer: " + d);

doubleConsumer.accept(3.14);

// IntFunction<R>

IntFunction<String> intFunction = i -> "Int Function Result: " + i;

System.out.println("IntFunction: " + intFunction.apply(10));

// LongFunction<R>

LongFunction<String> longFunction = l -> "Long Function Result: " + l;

System.out.println("LongFunction: " + longFunction.apply(10000000000L));

// DoubleFunction<R>

DoubleFunction<String> doubleFunction = d -> "Double Function Result: " + d;

System.out.println("DoubleFunction: " + doubleFunction.apply(2.71));

// IntToDoubleFunction

IntToDoubleFunction intToDoubleFunction = i -> i * 1.5;

System.out.println("IntToDoubleFunction: " + intToDoubleFunction.applyAsDouble(10));

// IntToLongFunction

IntToLongFunction intToLongFunction = i -> i * 1000L;

System.out.println("IntToLongFunction: " + intToLongFunction.applyAsLong(10));

// LongToDoubleFunction

LongToDoubleFunction longToDoubleFunction = l -> l / 2.0;


System.out.println("LongToDoubleFunction: " + longToDoubleFunction.applyAsDouble(100L));

// LongToIntFunction

LongToIntFunction longToIntFunction = l -> (int) (l % 100);

System.out.println("LongToIntFunction: " + longToIntFunction.applyAsInt(123456789L));

// DoubleToIntFunction

DoubleToIntFunction doubleToIntFunction = d -> (int) d;

System.out.println("DoubleToIntFunction: " + doubleToIntFunction.applyAsInt(3.99));

// DoubleToLongFunction

DoubleToLongFunction doubleToLongFunction = d -> (long) d;

System.out.println("DoubleToLongFunction: " + doubleToLongFunction.applyAsLong(7.99));

// DoubleToDoubleFunction

DoubleToDoubleFunction doubleToDoubleFunction = d -> d * 2;

System.out.println("DoubleToDoubleFunction: " + doubleToDoubleFunction.applyAsDouble(5.5));

// ToIntFunction<T>

ToIntFunction<String> toIntFunction = s -> s.length();

System.out.println("ToIntFunction: " + toIntFunction.applyAsInt("Hello"));

// ToLongFunction<T>

ToLongFunction<String> toLongFunction = s -> s.length();

System.out.println("ToLongFunction: " + toLongFunction.applyAsLong("Hello"));

// ToDoubleFunction<T>
ToDoubleFunction<String> toDoubleFunction = s -> s.length();

System.out.println("ToDoubleFunction: " + toDoubleFunction.applyAsDouble("Hello"));

Consumer: Hello, Consumer!

Function: Number: 10

Supplier: Hello, Supplier!

Predicate: true

UnaryOperator: 10

BinaryOperator: 7

BiConsumer: Age, 30

BiFunction: John is 25 years old

ObjIntConsumer: Score, 95

ObjLongConsumer: ID, 123456789

ObjDoubleConsumer: Value, 9.99

IntConsumer: 42

LongConsumer: 123456789

DoubleConsumer: 3.14

IntFunction: Int Function Result: 10

LongFunction: Long Function Result: 10000000000

DoubleFunction: Double Function Result: 2.71

IntToDoubleFunction: 15.0

IntToLongFunction: 10000
LongToDoubleFunction: 50.0

LongToIntFunction: 89

DoubleToIntFunction: 3

DoubleToLongFunction: 7

DoubleToDoubleFunction: 11.0

ToIntFunction: 5

ToLongFunction: 5

ToDoubleFunction: 5.0

public class WrapperClassesExample {

public static void main(String[] args) {

// Byte

Byte byteValue = 10;

System.out.println("Byte methods:");

System.out.println("byteValue(): " + byteValue.byteValue());

System.out.println("shortValue(): " + byteValue.shortValue());

System.out.println("intValue(): " + byteValue.intValue());

System.out.println("longValue(): " + byteValue.longValue());

System.out.println("floatValue(): " + byteValue.floatValue());

System.out.println("doubleValue(): " + byteValue.doubleValue());

System.out.println("compareTo(Byte): " + byteValue.compareTo((byte) 10));

System.out.println("equals(Byte): " + byteValue.equals((byte) 10));

System.out.println("hashCode(): " + byteValue.hashCode());


System.out.println("toString(): " + byteValue.toString());

System.out.println("parseByte(\"20\"): " + Byte.parseByte("20"));

System.out.println("valueOf(\"20\"): " + Byte.valueOf("20"));

System.out.println("valueOf(byte 20): " + Byte.valueOf((byte) 20));

System.out.println("decode(\"0x14\"): " + Byte.decode("0x14"));

System.out.println();

// Short

Short shortValue = 100;

System.out.println("Short methods:");

System.out.println("shortValue(): " + shortValue.shortValue());

System.out.println("intValue(): " + shortValue.intValue());

System.out.println("longValue(): " + shortValue.longValue());

System.out.println("floatValue(): " + shortValue.floatValue());

System.out.println("doubleValue(): " + shortValue.doubleValue());

System.out.println("compareTo(Short): " + shortValue.compareTo((short) 100));

System.out.println("equals(Short): " + shortValue.equals((short) 100));

System.out.println("hashCode(): " + shortValue.hashCode());

System.out.println("toString(): " + shortValue.toString());

System.out.println("parseShort(\"200\"): " + Short.parseShort("200"));

System.out.println("valueOf(\"200\"): " + Short.valueOf("200"));

System.out.println("valueOf(short 200): " + Short.valueOf((short) 200));

System.out.println("decode(\"0xC8\"): " + Short.decode("0xC8"));

System.out.println();

// Integer

Integer intValue = 1000;


System.out.println("Integer methods:");

System.out.println("intValue(): " + intValue.intValue());

System.out.println("longValue(): " + intValue.longValue());

System.out.println("floatValue(): " + intValue.floatValue());

System.out.println("doubleValue(): " + intValue.doubleValue());

System.out.println("compareTo(Integer): " + intValue.compareTo(1000));

System.out.println("equals(Integer): " + intValue.equals(1000));

System.out.println("hashCode(): " + intValue.hashCode());

System.out.println("toString(): " + intValue.toString());

System.out.println("parseInt(\"1000\"): " + Integer.parseInt("1000"));

System.out.println("valueOf(\"1000\"): " + Integer.valueOf("1000"));

System.out.println("valueOf(int 1000): " + Integer.valueOf(1000));

System.out.println("decode(\"0x3E8\"): " + Integer.decode("0x3E8"));

System.out.println();

// Long

Long longValue = 100000L;

System.out.println("Long methods:");

System.out.println("longValue(): " + longValue.longValue());

System.out.println("floatValue(): " + longValue.floatValue());

System.out.println("doubleValue(): " + longValue.doubleValue());

System.out.println("compareTo(Long): " + longValue.compareTo(100000L));

System.out.println("equals(Long): " + longValue.equals(100000L));

System.out.println("hashCode(): " + longValue.hashCode());

System.out.println("toString(): " + longValue.toString());

System.out.println("parseLong(\"100000\"): " + Long.parseLong("100000"));

System.out.println("valueOf(\"100000\"): " + Long.valueOf("100000"));


System.out.println("valueOf(long 100000): " + Long.valueOf(100000L));

System.out.println("decode(\"0x186A0\"): " + Long.decode("0x186A0"));

System.out.println();

// Float

Float floatValue = 3.14f;

System.out.println("Float methods:");

System.out.println("floatValue(): " + floatValue.floatValue());

System.out.println("doubleValue(): " + floatValue.doubleValue());

System.out.println("compareTo(Float): " + floatValue.compareTo(3.14f));

System.out.println("equals(Float): " + floatValue.equals(3.14f));

System.out.println("hashCode(): " + floatValue.hashCode());

System.out.println("toString(): " + floatValue.toString());

System.out.println("parseFloat(\"3.14\"): " + Float.parseFloat("3.14"));

System.out.println("valueOf(\"3.14\"): " + Float.valueOf("3.14"));

System.out.println("valueOf(float 3.14): " + Float.valueOf(3.14f));

System.out.println();

// Double

Double doubleValue = 3.14159;

System.out.println("Double methods:");

System.out.println("doubleValue(): " + doubleValue.doubleValue());

System.out.println("compareTo(Double): " + doubleValue.compareTo(3.14159));

System.out.println("equals(Double): " + doubleValue.equals(3.14159));

System.out.println("hashCode(): " + doubleValue.hashCode());

System.out.println("toString(): " + doubleValue.toString());

System.out.println("parseDouble(\"3.14159\"): " + Double.parseDouble("3.14159"));


System.out.println("valueOf(\"3.14159\"): " + Double.valueOf("3.14159"));

System.out.println("valueOf(double 3.14159): " + Double.valueOf(3.14159));

System.out.println();

// Character

Character charValue = 'A';

System.out.println("Character methods:");

System.out.println("charValue(): " + charValue.charValue());

System.out.println("compareTo(Character): " + charValue.compareTo('A'));

System.out.println("equals(Character): " + charValue.equals('A'));

System.out.println("hashCode(): " + charValue.hashCode());

System.out.println("toString(): " + charValue.toString());

System.out.println("isLetter('A'): " + Character.isLetter('A'));

System.out.println("isDigit('5'): " + Character.isDigit('5'));

System.out.println("isLetterOrDigit('A'): " + Character.isLetterOrDigit('A'));

System.out.println("isWhitespace(' '): " + Character.isWhitespace(' '));

System.out.println("digit('5', 10): " + Character.digit('5', 10));

System.out.println("forDigit(5, 10): " + Character.forDigit(5, 10));

System.out.println();

// Boolean

Boolean booleanValue = true;

System.out.println("Boolean methods:");

System.out.println("booleanValue(): " + booleanValue.booleanValue());

System.out.println("compareTo(Boolean): " + booleanValue.compareTo(false));

System.out.println("equals(Boolean): " + booleanValue.equals(true));

System.out.println("hashCode(): " + booleanValue.hashCode());


System.out.println("toString(): " + booleanValue.toString());

System.out.println("parseBoolean(\"true\"): " + Boolean.parseBoolean("true"));

System.out.println("valueOf(\"true\"): " + Boolean.valueOf("true"));

System.out.println("valueOf(boolean true): " + Boolean.valueOf(true));

Byte methods:

byteValue(): 10

shortValue(): 10

intValue(): 10

longValue(): 10

floatValue(): 10.0

doubleValue(): 10.0

compareTo(Byte): 0

equals(Byte): true

hashCode(): 10

toString(): 10

parseByte("20"): 20

valueOf("20"): 20

valueOf(byte 20): 20

decode("0x14"): 20

Short methods:
shortValue(): 100

intValue(): 100

longValue(): 100

floatValue(): 100.0

doubleValue(): 100.0

compareTo(Short): 0

equals(Short): true

hashCode(): 100

toString(): 100

parseShort("200"): 200

valueOf("200"): 200

valueOf(short 200): 200

decode("0xC8"): 200

Integer methods:

intValue(): 1000

longValue(): 1000

floatValue(): 1000.0

doubleValue(): 1000.0

compareTo(Integer): 0

equals(Integer): true

hashCode(): 1000

toString(): 1000

parseInt("1000"): 1000

valueOf("1000"): 1000

valueOf(int 1000): 1000

decode("0x3E8"): 1000
Long methods:

longValue(): 100000

floatValue(): 100000.0

doubleValue(): 100000.0

compareTo(Long): 0

equals(Long): true

hashCode(): 100000

toString(): 100000

parseLong("100000"): 100000

valueOf("100000"): 100000

valueOf(long 100000): 100000

decode("0x186A0"): 100000

Float methods:

floatValue(): 3.14

doubleValue(): 3.14

compareTo(Float): 0

equals(Float): true

hashCode(): 1078523331

toString(): 3.14

parseFloat("3.14"): 3.14

valueOf("3.14"): 3.14

valueOf(float 3.14): 3.14

Double methods:

doubleValue(): 3.14159
compareTo(Double): 0

equals(Double): true

hashCode(): 1079255761

toString(): 3.14159

parseDouble("3.14159"): 3.14159

valueOf("3.14159"): 3.14159

valueOf(double 3.14159): 3.14159

Character methods:

charValue(): A

compareTo(Character): 0

equals(Character): true

hashCode(): 65

toString(): A

isLetter('A'): true

isDigit('5'): true

isLetterOrDigit('A'): true

isWhitespace(' '): true

digit('5', 10): 5

forDigit(5, 10): 5

Boolean methods:

booleanValue(): true

compareTo(Boolean): 1

equals(Boolean): true

hashCode(): 1231

toString(): true
parseBoolean("true"): true

valueOf("true"): true

valueOf(boolean true): true

public class MathClassExample {

public static void main(String[] args) {

// Sample values

int int1 = 10, int2 = 20;

long long1 = 100L, long2 = 200L;

float float1 = 5.5f, float2 = 10.5f;

double double1 = 15.7, double2 = 25.9;

double angle = Math.toRadians(30); // for trigonometric functions

// Math class methods

System.out.println("Math methods:");

// abs

System.out.println("abs(int 10): " + Math.abs(int1));

System.out.println("abs(long 100L): " + Math.abs(long1));

System.out.println("abs(float 5.5f): " + Math.abs(float1));

System.out.println("abs(double 15.7): " + Math.abs(double1));

// acos

System.out.println("acos(0.5): " + Math.acos(0.5));


// asin

System.out.println("asin(0.5): " + Math.asin(0.5));

// atan

System.out.println("atan(1.0): " + Math.atan(1.0));

// atan2

System.out.println("atan2(1.0, 1.0): " + Math.atan2(1.0, 1.0));

// ceil

System.out.println("ceil(15.7): " + Math.ceil(double1));

// copySign

System.out.println("copySign(15.7, -1.0): " + Math.copySign(double1, -1.0));

// cos

System.out.println("cos(30 degrees): " + Math.cos(angle));

// cosh

System.out.println("cosh(1.0): " + Math.cosh(1.0));

// exp

System.out.println("exp(1.0): " + Math.exp(1.0));

// expm1

System.out.println("expm1(1.0): " + Math.expm1(1.0));


// floor

System.out.println("floor(15.7): " + Math.floor(double1));

// fma

System.out.println("fma(1.0, 2.0, 3.0): " + Math.fma(1.0, 2.0, 3.0));

// fmod

System.out.println("fmod(10.0, 3.0): " + Math.IEEEremainder(10.0, 3.0));

// hypot

System.out.println("hypot(3.0, 4.0): " + Math.hypot(3.0, 4.0));

// log

System.out.println("log(10.0): " + Math.log(10.0));

// log10

System.out.println("log10(100.0): " + Math.log10(100.0));

// log1p

System.out.println("log1p(1.0): " + Math.log1p(1.0));

// max

System.out.println("max(10, 20): " + Math.max(int1, int2));

System.out.println("max(100L, 200L): " + Math.max(long1, long2));

System.out.println("max(5.5f, 10.5f): " + Math.max(float1, float2));

System.out.println("max(15.7, 25.9): " + Math.max(double1, double2));


// min

System.out.println("min(10, 20): " + Math.min(int1, int2));

System.out.println("min(100L, 200L): " + Math.min(long1, long2));

System.out.println("min(5.5f, 10.5f): " + Math.min(float1, float2));

System.out.println("min(15.7, 25.9): " + Math.min(double1, double2));

// nextAfter

System.out.println("nextAfter(15.7, 20.0): " + Math.nextAfter(double1, 20.0));

// nextUp

System.out.println("nextUp(15.7): " + Math.nextUp(double1));

// pow

System.out.println("pow(2.0, 3.0): " + Math.pow(2.0, 3.0));

// random

System.out.println("random(): " + Math.random());

// round

System.out.println("round(15.7f): " + Math.round(float1));

System.out.println("round(15.7): " + Math.round(double1));

// signum

System.out.println("signum(-15.7): " + Math.signum(-15.7));

// sin
System.out.println("sin(30 degrees): " + Math.sin(angle));

// sinh

System.out.println("sinh(1.0): " + Math.sinh(1.0));

// sqrt

System.out.println("sqrt(16.0): " + Math.sqrt(16.0));

// tan

System.out.println("tan(30 degrees): " + Math.tan(angle));

// tanh

System.out.println("tanh(1.0): " + Math.tanh(1.0));

// toDegrees

System.out.println("toDegrees(π/6): " + Math.toDegrees(Math.PI / 6));

// toRadians

System.out.println("toRadians(30 degrees): " + Math.toRadians(30));

// ulp

System.out.println("ulp(15.7): " + Math.ulp(double1));

}
Math methods:

abs(int 10): 10

abs(long 100L): 100

abs(float 5.5f): 5.5

abs(double 15.7): 15.7

acos(0.5): 1.0471975511965979

asin(0.5): 0.5235987755982989

atan(1.0): 0.7853981633974483

atan2(1.0, 1.0): 0.7853981633974483

ceil(15.7): 16.0

copySign(15.7, -1.0): -15.7

cos(30 degrees): 0.8660254037844387

cosh(1.0): 1.5430806348152437

exp(1.0): 2.718281828459045

expm1(1.0): 1.718281828459045

floor(15.7): 15.0

fma(1.0, 2.0, 3.0): 5.0

fmod(10.0, 3.0): 1.0

hypot(3.0, 4.0): 5.0

log(10.0): 2.302585092994046

log10(100.0): 2.0

log1p(1.0): 0.6931471805599453

max(10, 20): 20

max(100L, 200L): 200

max(5.5f, 10.5f): 10.5

max(15.7, 25.9): 25.9


min(10, 20): 10

min(100L, 200L): 100

min(5.5f, 10.5f): 5.5

min(15.7, 25.9): 15.7

nextAfter(15.7, 20.0): 15.700000000000001

nextUp(15.7): 15.700000000000001

pow(2.0, 3.0): 8.0

random(): 0.7128546987948636

round(15.7f): 16

round(15.7): 16

signum(-15.7): -1.0

sin(30 degrees): 0.49999999999999994

sinh(1.0): 1.1752011936438014

sqrt(16.0): 4.0

tan(30 degrees): 0.5773502691896257

tanh(1.0): 0.7615941559557649

toDegrees(π/6): 30.0

toRadians(30 degrees): 0.5235987755982988

ulp(15.7): 1.421085471520234e-14

public class ThreadMethodsExample {


public static void main(String[] args) {

// Create a new thread

Thread thread = new Thread(() -> {

try {

System.out.println("Thread started.");

// Print thread details

System.out.println("Thread Name: " + Thread.currentThread().getName());

System.out.println("Thread Priority: " + Thread.currentThread().getPriority());

System.out.println("Thread State: " + Thread.currentThread().getState());

// Sleep for 2 seconds

System.out.println("Thread sleeping for 2 seconds...");

Thread.sleep(2000);

// Print formatted output

System.out.printf("Formatted number: %.2f%n", 3.14159);

// Yield execution to other threads

System.out.println("Thread yielding...");

Thread.yield();

// Check if the thread was interrupted

if (Thread.currentThread().isInterrupted()) {

System.out.println("Thread was interrupted.");

} else {
System.out.println("Thread was not interrupted.");

// Interrupt the thread itself

Thread.currentThread().interrupt();

// Check if the thread was interrupted again

if (Thread.currentThread().isInterrupted()) {

System.out.println("Thread was interrupted after setting.");

// Print thread details again

System.out.println("Thread State after interrupt: " + Thread.currentThread().getState());

} catch (InterruptedException e) {

System.out.println("Thread was interrupted during sleep.");

// Print thread details at the end

System.out.println("Thread ended.");

});

// Set thread properties

thread.setName("ExampleThread");

thread.setPriority(Thread.MAX_PRIORITY);

// Print thread details before starting


System.out.println("Thread State before start: " + thread.getState());

System.out.println("Thread Name: " + thread.getName());

System.out.println("Thread Priority: " + thread.getPriority());

// Start the thread

thread.start();

try {

// Wait for the thread to complete

thread.join();

} catch (InterruptedException e) {

System.out.println("Main thread was interrupted while waiting.");

// Print thread details after completion

System.out.println("Thread State after completion: " + thread.getState());

System.out.println("Main thread ending.");

Thread State before start: NEW

Thread Name: ExampleThread

Thread Priority: 10

Thread started.
Thread Name: ExampleThread

Thread Priority: 10

Thread State: RUNNABLE

Thread sleeping for 2 seconds...

Thread yielding...

Thread was not interrupted.

Formatted number: 3.14

Thread State after interrupt: RUNNABLE

Thread ended.

Thread State after completion: TERMINATED

Main thread ending.

public class RunnableExample implements Runnable {

// Implementing the run() method from Runnable interface

@Override

public void run() {

// Code that will be executed by the thread

System.out.println("Thread is running.");

try {

// Simulate some work with sleep

Thread.sleep(1000); // Sleep for 1 second

System.out.println("Thread is still running after 1 second.");


} catch (InterruptedException e) {

System.out.println("Thread was interrupted.");

public static void main(String[] args) {

// Create an instance of RunnableExample

RunnableExample runnableExample = new RunnableExample();

// Create a new thread and pass the Runnable instance

Thread thread = new Thread(runnableExample);

// Start the thread

thread.start();

try {

// Wait for the thread to complete

thread.join();

System.out.println("Thread has completed.");

} catch (InterruptedException e) {

System.out.println("Main thread was interrupted while waiting.");

}
Thread is running.

Thread is still running after 1 second.

Thread has completed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy