Skip to content

Commit

Permalink
Merge pull request VarshaDas#7 from VarshaDas/streams
Browse files Browse the repository at this point in the history
Streams, optionals
  • Loading branch information
VarshaDas authored Mar 18, 2024
2 parents 8845078 + a9287c3 commit e246877
Show file tree
Hide file tree
Showing 19 changed files with 774 additions and 46 deletions.
108 changes: 108 additions & 0 deletions ArraysDemo/ArrayAndCollectionTasks.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
//import java.util.*;
//
//public class ArraysAndCollectionTasks {
//
// public static void main(String[] args) {
// // Question 1: Sorting an Array of Integers
// int[] array1 = {3, 1, 4, 1, 5, 9, 2, 6};
// Arrays.sort(array1);
// System.out.println("Sorted Array: " + Arrays.toString(array1));
//
// // Question 2: Checking for Equality of Two Arrays
// int[] array2 = {1, 2, 3};
// boolean equal = Arrays.equals(array1, array2);
// System.out.println("Are arrays equal? " + equal);
//
// // Question 3: Finding the Maximum Element in an ArrayList
// ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6));
// int max = Collections.max(list);
// System.out.println("Maximum element in ArrayList: " + max);
//
// // Question 4: Shuffling Elements of an ArrayList
// Collections.shuffle(list);
// System.out.println("Shuffled ArrayList: " + list);
//
// // Question 5: Finding the Frequency of an Element in an ArrayList
// int frequency = Collections.frequency(list, 1);
// System.out.println("Frequency of '1' in ArrayList: " + frequency);
//
// // Question 6: Checking if an ArrayList is Empty
// boolean isEmpty = list.isEmpty();
// System.out.println("Is ArrayList empty? " + isEmpty);
//
// // Question 7: Converting Array to ArrayList
// String[] array3 = {"apple", "banana", "orange"};
// ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array3));
// String newarr[] = arrayList.toArray(new String[0]);
// System.out.println(newarr);
// System.out.println("ArrayList from Array: " + arrayList);
//
// // Question 8: Reversing an Array
// Collections.reverse(Arrays.asList(array3));
// System.out.println("Reversed Array: " + Arrays.toString(array3));
//
// // Question 9: Removing All Occurrences of an Element from an ArrayList
// list.removeAll(Collections.singleton(1));
// System.out.println("ArrayList after removing all occurrences of '1': " + list);
//
// // Question 10: Copying Elements from ArrayList to Array
// Integer[] array4 = list.toArray(new Integer[0]);
// System.out.println("Copied Array: " + Arrays.toString(array4));
//
//
// // Question 1: Removing Null Values from an ArrayList
// ArrayList<String> stringList = new ArrayList<>(Arrays.asList("apple", null, "banana", null, "orange"));
// stringList.removeAll(Collections.singleton(null));
// System.out.println("1. List after removing null values: " + stringList);
//
// // Question 2: Finding the Average of an Array
// int[] numbers = {1, 2, 3, 4, 5};
// double average = Arrays.stream(numbers).average().orElse(Double.NaN);
// System.out.println("2. Average of the array: " + average);
//
// // Question 3: Checking for Palindromes in an ArrayList
// ArrayList<String> wordList = new ArrayList<>(Arrays.asList("radar", "apple", "level", "banana"));
// for (String word : wordList) {
// boolean isPalindrome = new StringBuilder(word).reverse().toString().equalsIgnoreCase(word);
// System.out.println("3. " + word + " is a palindrome: " + isPalindrome);
// }
//
// // Question 4: Merging Two Arrays into a Single Array
// int[] array1 = {1, 2, 3};
// int[] array2 = {4, 5, 6};
// int[] mergedArray = new int[array1.length + array2.length];
// System.arraycopy(array1, 0, mergedArray, 0, array1.length);
// System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
// System.out.println("4. Merged array: " + Arrays.toString(mergedArray));
//
// // Question 5: Finding the Mode of an ArrayList
// ArrayList<Integer> numberList = new ArrayList<>(Arrays.asList(1, 2, 3, 2, 4, 5, 2, 6, 7, 2, 8, 9, 2));
// int mode = numberList.stream().max(Comparator.comparingInt(Collections::frequency)).orElse(null);
// System.out.println("5. Mode of the list: " + mode);
//
// // Question 6: Rotating an Array
// int[] arrayToRotate = {1, 2, 3, 4, 5};
// int rotateBy = 2;
// int[] rotatedArray = new int[arrayToRotate.length];
// for (int i = 0; i < arrayToRotate.length; i++) {
// rotatedArray[(i + rotateBy) % arrayToRotate.length] = arrayToRotate[i];
// }
// System.out.println("6. Rotated array: " + Arrays.toString(rotatedArray));
//
// // Question 7: Removing Even Numbers from an ArrayList
// ArrayList<Integer> integerList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
// integerList.removeIf(num -> num % 2 == 0);
// System.out.println("7. List after removing even numbers: " + integerList);
//
// // Question 8: Finding the Intersection of Two Arrays
// int[] arrayA = {1, 2, 3, 4, 5};
// int[] arrayB = {3, 4, 5, 6, 7};
// Set<Integer> intersection = new HashSet<>();
// for (int num : arrayA) {
// if (Arrays.binarySearch(arrayB, num) >= 0) {
// intersection.add(num);
// }
// }
// System.out.println("8. Intersection of arrays: " + intersection);
// }
//}
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ public static void main(String[] args) {

List<String> fruitsMix = Arrays.asList("APPLE", "cherry", "baNaNa", "pineapple", "KiWI", "elderberry");
Comparator<String> caseInsensitiveComp = String.CASE_INSENSITIVE_ORDER;
// fruitsMix.sort(caseInsensitiveComp);
Collections.sort(fruitsMix);
fruitsMix.sort(caseInsensitiveComp);

System.out.println(fruitsMix);

Expand Down
File renamed without changes.
File renamed without changes.
33 changes: 33 additions & 0 deletions ArraysDemo/LinkedHashMapDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapDemo {

public static void main(String[] args) {
// Create a LinkedHashMap with access order set to true
Map<String, Integer> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true);
//Map<String, Integer> linkedHashMap = new LinkedHashMap<>(16, 0.75f, false);

// Add elements to the LinkedHashMap
linkedHashMap.put("One", 1);
linkedHashMap.put("Two", 2);
linkedHashMap.put("Three", 3);
linkedHashMap.put("Four", 4);

// Print the elements in insertion order
System.out.println("LinkedHashMap elements in insertion order:");
printMap(linkedHashMap);

// Access an element to change the access order
System.out.println("\nAccessing an element to change access order: "+linkedHashMap.get("Two"));

// Print the elements again to show access order
System.out.println("\nLinkedHashMap elements after accessing an element (access order):");
printMap(linkedHashMap);
}

private static void printMap(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
File renamed without changes.
6 changes: 3 additions & 3 deletions LambdasAndStreams/pom.xml → Java8/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>LambdasAndStreams</artifactId>
<artifactId>Java8</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
Expand Down
35 changes: 35 additions & 0 deletions Java8/src/main/java/Optionals/OptionalCodeDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package Optionals;

public class OptionalCodeDemo {
public static void main(String[] args) {
// Example 1: Creating an Optional with a non-null value


// Example 2: Creating an empty Optional


// Example 3: Creating an Optional with a potentially null value


// Example 4: Checking if Optional contains a value


// Example 5: Default value if Optional is empty


// Example 6: Default value supplier if Optional is empty


// Example 7: Throw exception if Optional is empty


// Example 8: Filter and map operations on Optional


// Example 9: Chaining methods on Optional


// Example 10: Transforming Optional to Stream

}
}
67 changes: 67 additions & 0 deletions Java8/src/main/java/Optionals/OptionalDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package Optionals;

import java.util.NoSuchElementException;
import java.util.Optional;

public class OptionalDemo {

public static void main(String[] args) {
// Example 1: Creating an Optional with a non-null value
Optional<String> optional1 = Optional.of("Hello");
System.out.println("1. Optional with non-null value: " + optional1);

// Example 2: Creating an empty Optional
Optional<String> optional2 = Optional.empty();
System.out.println("2. Empty Optional: " + optional2);

// Example 3: Creating an Optional with a potentially null value
String str = "World";
Optional<String> optional3 = Optional.ofNullable(null);
System.out.println("3. Optional with potentially null value: " + optional3);

// Example 4: Checking if Optional contains a value
if (optional3.isPresent()) {
System.out.println("4. Optional contains a value: " + optional3.get());
} else {
System.out.println("4. Optional is empty");
}

// Example 5: Default value if Optional is empty
String value = optional2.orElse("Default Value");
System.out.println("5. Value of Optional (or default): " + value);

// Example 6: Default value supplier if Optional is empty
String valueSupplier = optional2.orElseGet(() -> "Default Value from Supplier");
System.out.println("6. Value of Optional (or default from supplier): " + valueSupplier);

// Example 7: Throw exception if Optional is empty
try {
String valueOrThrow = optional2.orElseThrow(() -> new NoSuchElementException("Optional is empty"));
System.out.println("7. Value of Optional (or throw exception): " + valueOrThrow);
} catch (NoSuchElementException e) {
System.out.println("7. " + e.getMessage());
}

// Example 8: Filter and map operations on Optional
Optional<Integer> optionalInt = Optional.of(10);
Optional<Integer> filtered = optionalInt.filter(x -> x > 5);
Optional<String> mapped = filtered.map(Object::toString);
System.out.println("8. Filtered and mapped value: " + mapped.orElse("Empty"));

// Example 9: Chaining methods on Optional
String result = Optional.of("Hello")
.map(s -> s + " World")
.filter(s -> s.length() > 5)
.orElse("Too short");
System.out.println("9. Chained methods result: " + result);

// Example 10: Transforming Optional to Stream
Optional<String> optionalString = Optional.of("Transform");
optionalString.stream().forEach(System.out::println);

Optional<String> optional = Optional.of("hello");
optional.ifPresent(val -> System.out.println("Value: " + value));
}
}


58 changes: 58 additions & 0 deletions Java8/src/main/java/Optionals/OptionalREADME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
**README.md**

# Optional in Java

## What is Optional?

`Optional` is a container object that may or may not contain a non-null value. It was introduced in Java 8 as part of the `java.util` package to represent optional values and to deal with the problem of null references in a more effective and expressive way.

## Why Optional?

Prior to the introduction of `Optional` in Java 8, handling null values often led to NullPointerExceptions (NPEs), which could be difficult to debug and manage. `Optional` provides a more explicit and safer way to handle the absence of a value, reducing the likelihood of NPEs and improving code clarity and robustness.

## Before Optional

Before the introduction of `Optional`, developers commonly used null references to represent the absence of a value. This approach often resulted in code that was hard to read, maintain, and debug. Null checks were required everywhere, leading to verbose and error-prone code. Additionally, it was not always clear whether a method could return null or not, making it challenging to reason about the behavior of the code.

## Problems Solved by Optional

### 1. Null Pointer Safety
- `Optional` provides a safer alternative to null references, reducing the risk of NullPointerExceptions and improving code reliability.

### 2. Improved Code Readability
- By using `Optional`, code becomes more expressive and self-documenting, as it clearly indicates whether a value may be absent or present.

### 3. Forced Null Checking
- `Optional` encourages developers to explicitly handle the case of a missing value, either by providing a default value or performing an alternative action, thus promoting defensive programming practices.

## Basic Methods

### Creation:
- `Optional.of(T value)`: Creates an `Optional` with the specified non-null value, throwing a NullPointerException if the value is null.
- `Optional.ofNullable(T value)`: Creates an `Optional` with the specified value, which may be null.

### Checking for Presence:
- `isPresent()`: Returns true if the `Optional` contains a non-null value.
- `isEmpty()`: Returns true if the `Optional` is empty.

### Getting the Value:
- `get()`: Returns the value if present, otherwise throws a NoSuchElementException.

### Conditional Retrieval:
- `orElse(T other)`: Returns the value if present, otherwise returns the specified default value.
- `orElseGet(Supplier<? extends T> other)`: Returns the value if present, otherwise invokes the specified supplier and returns its result.
- `orElseThrow()`: Returns the value if present, otherwise throws the specified exception.

### Mapping and Filtering:
- `map(Function<? super T, ? extends U> mapper)`: Applies the specified mapping function to the value if present.
- `flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)`: Applies the specified mapping function to the value if present and returns the result.
- `filter(Predicate<? super T> predicate)`: If a value is present, applies the given predicate to it, and returns an `Optional` describing the value if the predicate returns true.

### Utility Methods:
- `ifPresent(Consumer<? super T> consumer)`: If a value is present, performs the given action with the value.
- `ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)`: If a value is present, performs the given action with the value, otherwise performs the specified empty action.
- `equals(Object obj)`: Indicates whether some other object is "equal to" this Optional.

## Conclusion

`Optional` provides a more structured and reliable approach to handling optional values in Java, addressing common pitfalls associated with null references. By encouraging explicit handling of absent values and providing a rich set of methods for working with optionals, `Optional` improves code clarity, safety, and maintainability.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit e246877

Please sign in to comment.