Saravanan's Corner: Blackberry Dev

Thursday, 10 July 2025

Java Stream API interview coding questions

 Java Stream API interview coding questions and uncover the secrets to mastering this powerful API!

  1. Write a program to find the sum of all elements in a list using Java Stream API
import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
}
}

Output:
Sum: 15

2. Given a list of integers, write a program to find and print the maximum element using Java Stream API

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 4, 8, 6, 10);
int max = numbers.stream()
.mapToInt(Integer::intValue)
.max()
.orElseThrow();
System.out.println("Max element: " + max);
}
}

Output:
Max element: 10

3. Write a program to filter out all the even numbers from a list using Java Stream API

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
}
}

Output:
Even numbers: [2, 4]

4. Given a list of strings, write a program to count the number of strings containing a specific character ‘a’ using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
char searchChar = 'a';
long count = strings.stream()
.filter(str -> str.contains(String.valueOf(searchChar)))
.count();
System.out.println("Number of strings containing '" + searchChar + "': " + count);
}
}

Output:
Number of strings containing 'a': 4

5. Write a program to convert a list of strings to uppercase using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
List<String> upperCaseStrings = strings.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Uppercase strings: " + upperCaseStrings);
}
}

Output:
Uppercase strings: [APPLE, BANANA, ORANGE, GRAPE]

6. Given a list of integers, write a program to calculate the average of all the numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
OptionalDouble average = numbers.stream()
.mapToDouble(Integer::doubleValue)
.average();
System.out.println("Average: " + (average.isPresent() ? average.getAsDouble() : "N/A"));
}
}

Output:
Average: 3.0

7. Write a program to sort a list of strings in alphabetical order using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("banana", "orange", "apple", "grape");
List<String> sortedStrings = strings.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted strings: " + sortedStrings);
}
}

Output:
Sorted strings: [apple, banana, grape, orange]

8. Given a list of strings, write a program to concatenate all the strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
String concatenatedString = strings.stream()
.collect(Collectors.joining());
System.out.println("Concatenated string: " + concatenatedString);
}
}

Output:
Concatenated string: applebananaorangegrape

9. Write a program to find the longest string in a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "orange", "grape");
Optional<String> longestString = strings.stream()
.max((str1, str2) -> str1.length() - str2.length());
System.out.println("Longest string: " + (longestString.isPresent() ? longestString.get() : "N/A"));
}
}

Output:
Longest string: banana

10. Given a list of integers, write a program to find and print the second largest number using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(4, 2, 8, 6, 10);
Optional<Integer> secondLargest = numbers.stream()
.sorted((num1, num2) -> num2 - num1)
.skip(1)
.findFirst();
System.out.println("Second largest number: " + (secondLargest.isPresent() ? secondLargest.get() : "N/A"));
}
}

Output:
Second largest number: 8

11. Write a program to remove all the duplicate elements from a list using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Original list: " + numbers);
System.out.println("List with duplicates removed: " + uniqueNumbers);
}
}

Output:
Original list: [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1]
List with duplicates removed: [1, 2, 3, 4, 5, 6, 7, 8]

12. Given a list of strings, write a program to find and print the shortest string using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String shortestString = strings.stream()
.min(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println("Shortest string: " + shortestString);
}
}

Output:
Shortest string: kiwi

13. Write a program to convert a list of integers to a list of their squares using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println("Original list: " + numbers);
System.out.println("List of squares: " + squares);
}
}

Output:
Original list: [1, 2, 3, 4, 5]
List of squares: [1, 4, 9, 16, 25]

14. Given a list of strings, write a program to find and print the strings starting with a specific prefix ‘a’ using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String prefix = "a";
List<String> stringsWithPrefix = strings.stream()
.filter(s -> s.startsWith(prefix))
.collect(Collectors.toList());
System.out.println("Strings starting with prefix '" + prefix + "': " + stringsWithPrefix);
}
}

Output:
Strings starting with prefix 'a': [apple]

15. Write a program to find the product of all elements in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println("Product of all elements: " + product);
}
}

Output:
Product of all elements: 120

16. Given a list of integers, write a program to find and print the prime numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
List<Integer> primes = numbers.stream()
.filter(Main::isPrime)
.collect(Collectors.toList());
System.out.println("Prime numbers: " + primes);
}

private static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Output:
Prime numbers: [2, 3, 5, 7, 11]

17. Write a program to check if a list of strings contains a specific string using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String target = "banana";
boolean containsString = strings.stream()
.anyMatch(s -> s.equals(target));
System.out.println("List contains string '" + target + "': " + containsString);
}
}

Output:
List contains string 'banana': true

18. Given a list of strings, write a program to find and print the strings with length greater than a specified value 5 using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
int minLength = 5;
List<String> longStrings = strings.stream()
.filter(s -> s.length() > minLength)
.collect(Collectors.toList());
System.out.println("Strings with length greater than " + minLength + ": " + longStrings);
}
}

Output:
Strings with length greater than 5: [banana, orange]

19. Write a program to filter out all the elements divisible by 3 and 5 from a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
List<Integer> divisibleBy3And5 = numbers.stream()
.filter(n -> n % 3 == 0 && n % 5 == 0)
.collect(Collectors.toList());
System.out.println("Numbers divisible by 3 and 5: " + divisibleBy3And5);
}
}

Output:
Numbers divisible by 3 and 5: [15]

20. Given a list of strings, write a program to find and print the strings with the maximum length using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Optional<String> maxLengthString = strings.stream()
.max(Comparator.comparingInt(String::length));
maxLengthString.ifPresent(s -> System.out.println("String with maximum length: " + s));
}
}

Output:
String with maximum length: banana

21. Write a program to reverse a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Collections.reverse(strings);
System.out.println("Reversed list: " + strings);
}
}

Output:
Reversed list: [pear, orange, kiwi, banana, apple]

22. Given a list of integers, write a program to find and print the distinct odd numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> distinctOddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct odd numbers: " + distinctOddNumbers);
}
}

Output:
Distinct odd numbers: [1, 3, 5, 7, 9]

23. Write a program to remove all null values from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", null, "banana", null, "kiwi", "orange", null, "pear");
List<String> nonNullStrings = strings.stream()
.filter(s -> s != null)
.collect(Collectors.toList());
System.out.println("List with null values removed: " + nonNullStrings);
}
}

Output:
List with null values removed: [apple, banana, kiwi, orange, pear]

24. Given a list of integers, write a program to find and print the sum of all odd numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sumOfOddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of odd numbers: " + sumOfOddNumbers);
}
}

Output:
Sum of odd numbers: 25

25. Write a program to find the intersection of two lists of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
List<String> list2 = Arrays.asList("banana", "orange", "grape", "watermelon");
List<String> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println("Intersection of lists: " + intersection);
}
}

Output:
Intersection of lists: [banana, orange]

26. Given a list of strings, write a program to find and print the strings containing only vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear", "oai");
List<String> vowelStrings = strings.stream()
.filter(s -> s.matches("[aeiouAEIOU]+"))
.collect(Collectors.toList());
System.out.println("Strings containing only vowels: " + vowelStrings);
}
}

Output:
Strings containing only vowels: [oai]

27. Write a program to convert a list of strings to a comma-separated string using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String commaSeparatedString = strings.stream()
.collect(Collectors.joining(", "));
System.out.println("Comma-separated string: " + commaSeparatedString);
}
}

Output:
Comma-separated string: apple, banana, kiwi, orange, pear

28. Given a list of integers, write a program to find and print the index of the first occurrence of a specific number using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 3, 5, 7, 9, 2, 4, 6, 8, 10);
int targetNumber = 7;
int index = numbers.indexOf(targetNumber);
System.out.println("Index of " + targetNumber + ": " + index);
}
}

Output:
Index of 7: 3

29. Write a program to find the union of two lists of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8);
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println("Union of lists: " + union);
}
}

Output:
Union of lists: [1, 2, 3, 4, 5, 6, 7, 8]

30. Given a list of strings, write a program to find and print the strings containing duplicate characters using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear", "strawberry", "watermelon");
List<String> duplicateStrings = strings.stream()
.filter(s -> s.length() != s.chars().distinct().count())
.collect(Collectors.toList());
System.out.println("Strings containing duplicate characters: " + duplicateStrings);
}
}

Output:
Strings containing duplicate characters: [apple, banana, kiwi, strawberry, watermelon]

31. Write a program to check if all elements in a list of strings are of the same length using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
boolean sameLength = strings.stream()
.map(String::length)
.distinct()
.count() == 1;
System.out.println("All elements have the same length: " + sameLength);
}
}

Output:
All elements have the same length: false

32. Given a list of integers, write a program to find and print the difference between the maximum and minimum numbers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 5, 7, 18, 3, 15);
OptionalInt max = numbers.stream().mapToInt(Integer::intValue).max();
OptionalInt min = numbers.stream().mapToInt(Integer::intValue).min();
int difference = max.getAsInt() - min.getAsInt();
System.out.println("Difference between maximum and minimum numbers: " + difference);
}
}

Output:
Difference between maximum and minimum numbers: 15

33. Write a program to remove all whitespace from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "ba nana", "kiwi", "oran ge", "pear");
List<String> noWhitespace = strings.stream().map(s -> s.replaceAll("\\s", "")).collect(Collectors.toList());
System.out.println("List with whitespace removed: " + noWhitespace);
}
}

Output:
List with whitespace removed: [apple, banana, kiwi, orange, pear]

34. Given a list of strings, write a program to find and print the strings containing a specific substring using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
String substring = "an";
List<String> containingSubstring = strings.stream().filter(s -> s.contains(substring)).collect(Collectors.toList());
System.out.println("Strings containing \"" + substring + "\": " + containingSubstring);
}
}

Output:
Strings containing "an": [banana, orange]

35. Write a program to find the mode of a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long maxFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<Integer> modes = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Mode(s): " + modes);
}
}

Output:
Mode(s): [4]

36. Given a list of strings, write a program to find and print the strings with the minimum length using Java Stream API.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Optional<String> minLengthString = strings.stream().min(Comparator.comparingInt(String::length));
System.out.println("String with minimum length: " + minLengthString.orElse("No strings in the list"));
}
}

Output:
String with minimum length: kiwi

37. Write a program to find the frequency of each element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
System.out.println("Frequency of each element: " + frequencyMap);
}
}

Output:
Frequency of each element: {1=1, 2=1, 3=2, 4=3, 5=2}

38. Given a list of strings, write a program to find and print the strings with the maximum number of vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "AEIOUaeiou".indexOf(c) != -1).count()));
long maxVowelCount = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<String> maxVowelStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxVowelCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with maximum number of vowels: " + maxVowelStrings);
}
}

Output:
String(s) with maximum number of vowels: [banana, orange]

39. Write a program to check if a list of integers is sorted in ascending order using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 5, 4);
boolean sortedAscending = numbers.stream().sorted().collect(Collectors.toList()).equals(numbers);
System.out.println("Is the list sorted in ascending order? " + sortedAscending);
}
}

Output:
Is the list sorted in ascending order? false

40. Given a list of strings, write a program to find and print the strings with the minimum number of vowels using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "AEIOUaeiou".indexOf(c) != -1).count()));
long minVowelCount = frequencyMap.values().stream().mapToLong(Long::longValue).min().orElse(0);
List<String> minVowelStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == minVowelCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with minimum number of vowels: " + minVowelStrings);
}
}

Output:
String(s) with minimum number of vowels: [apple, kiwi, pear]

41. Write a program to find the median of a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
OptionalDouble median = numbers.stream().mapToInt(Integer::intValue).sorted()
.skip((numbers.size() - 1) / 2)
.limit(numbers.size() % 2 == 0 ? 2 : 1)
.average();
System.out.println("Median of the list: " + (median.isPresent() ? median.getAsDouble() : "N/A"));
}
}

Output:
Median of the list: 3.0

42. Given a list of strings, write a program to find and print the strings containing a specific character at least twice using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
char targetChar = 'a';
List<String> containingCharTwice = strings.stream()
.filter(s -> s.chars().filter(c -> c == targetChar).count() >= 2)
.collect(Collectors.toList());
System.out.println("Strings containing \"" + targetChar + "\" at least twice: " + containingCharTwice);
}
}

Output:
Strings containing "a" at least twice: [banana]

43. Write a program to find the kth smallest element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
int k = 3; // Find the 3rd smallest element
Optional<Integer> kthSmallest = numbers.stream().sorted().skip(k - 1).findFirst();
System.out.println("The " + k + "th smallest element: " + (kthSmallest.isPresent() ? kthSmallest.get() : "N/A"));
}
}

Output:
The 3th smallest element: 2

44. Given a list of strings, write a program to find and print the strings with the maximum number of consonants using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "orange", "pear");
Map<String, Long> frequencyMap = strings.stream()
.collect(Collectors.toMap(s -> s, s -> s.chars().filter(c -> "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz".indexOf(c) != -1).count()));
long maxConsonantCount = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<String> maxConsonantStrings = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxConsonantCount)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("String(s) with maximum number of consonants: " + maxConsonantStrings);
}
}

Output:
String(s) with maximum number of consonants: [banana, orange, apple]

45. Write a program to check if a list of strings is palindrome using Java Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("apple", "banana", "kiwi", "banana", "apple");
boolean isPalindrome = strings.stream()
.skip(strings.size() / 2)
.allMatch(s -> s.equals(strings.get(strings.size() - 1 - strings.indexOf(s))));
System.out.println("Is the list a palindrome? " + isPalindrome);
}
}

Output:
Is the list a palindrome? true

46. Given a list of integers, write a program to find and print the elements with the highest frequency using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long maxFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).max().orElse(0);
List<Integer> elementsWithMaxFrequency = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Element(s) with highest frequency: " + elementsWithMaxFrequency);
}
}

Output:
Element(s) with highest frequency: [4]

47. Write a program to remove all non-numeric characters from a list of strings using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("a1b2c3", "1a2b3c", "123abc");
Pattern pattern = Pattern.compile("[^0-9]");
List<String> numericStrings = strings.stream()
.map(s -> pattern.matcher(s).replaceAll(""))
.collect(Collectors.toList());
System.out.println("List with non-numeric characters removed: " + numericStrings);
}
}

Output:
List with non-numeric characters removed: [123, 123, 123]

48. Given a list of strings, write a program to find and print the strings containing only digits using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
public static void main(String[] args) {
List<String> strings = Arrays.asList("123", "abc", "456", "789", "def");
Predicate<String> containsOnlyDigits = s -> s.matches("\\d+");
List<String> digitStrings = strings.stream().filter(containsOnlyDigits).collect(Collectors.toList());
System.out.println("Strings containing only digits: " + digitStrings);
}
}

Output:
Strings containing only digits: [123, 456, 789]

49. Write a program to find the kth largest element in a list of integers using Java Stream API.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
int k = 3; // Find the 3rd largest element
Collections.sort(numbers, Collections.reverseOrder());
Integer kthLargest = numbers.stream().distinct().skip(k - 1).findFirst().orElse(null);
System.out.println("The " + k + "th largest element: " + kthLargest);
}
}

Output:
The 3th largest element: 5

50. Given a list of integers, write a program to find and print the elements with the lowest frequency using Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4, 4, 5, 5);
Map<Integer, Long> frequencyMap = numbers.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting()));
long minFrequency = frequencyMap.values().stream().mapToLong(Long::longValue).min().orElse(0);
List<Integer> elementsWithMinFrequency = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == minFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Element(s) with lowest frequency: " + elementsWithMinFrequency);
}
}

Output:
Element(s) with lowest frequency: [1, 2]

Thank you for taking the time to read this article.  

Wednesday, 26 February 2025

 <!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<style>

* {box-sizing: border-box}

body {font-family: Verdana, sans-serif; margin:0}

.mySlides {display: none}

img {vertical-align: middle;}


/* Slideshow container */

.slideshow-container {

  max-width: 1000px;

  position: relative;

  margin: auto;

}


/* Next & previous buttons */

.prev, .next {

  cursor: pointer;

  position: absolute;

  top: 50%;

  width: auto;

  padding: 16px;

  margin-top: -22px;

  color: white;

  font-weight: bold;

  font-size: 18px;

  transition: 0.6s ease;

  border-radius: 0 3px 3px 0;

  user-select: none;

}


/* Position the "next button" to the right */

.next {

  right: 0;

  border-radius: 3px 0 0 3px;

}


/* On hover, add a black background color with a little bit see-through */

.prev:hover, .next:hover {

  background-color: rgba(0,0,0,0.8);

}


/* Caption text */

.text {

  color: #f2f2f2;

  font-size: 15px;

  padding: 8px 12px;

  position: absolute;

  bottom: 8px;

  width: 100%;

  text-align: center;

}


/* Number text (1/3 etc) */

.numbertext {

  color: #f2f2f2;

  font-size: 12px;

  padding: 8px 12px;

  position: absolute;

  top: 0;

}


/* The dots/bullets/indicators */

.dot {

  cursor: pointer;

  height: 15px;

  width: 15px;

  margin: 0 2px;

  background-color: #bbb;

  border-radius: 50%;

  display: inline-block;

  transition: background-color 0.6s ease;

}


.active, .dot:hover {

  background-color: #717171;

}


/* Fading animation */

.fade {

  animation-name: fade;

  animation-duration: 1.5s;

}


@keyframes fade {

  from {opacity: .4} 

  to {opacity: 1}

}


/* On smaller screens, decrease text size */

@media only screen and (max-width: 300px) {

  .prev, .next,.text {font-size: 11px}

}

.btn-group button {

  background-color: #04AA6D; /* Green background */

  border: 1px solid green; /* Green border */

  color: white; /* White text */

  padding: 10px 24px; /* Some padding */

  cursor: pointer; /* Pointer/hand icon */

}


/* Clear floats (clearfix hack) */

.btn-group:after {

  content: "";

  clear: both;

  display: table;

}


.btn-group button:not(:last-child) {

  border-right: none; /* Prevent double borders */

}


/* Add a background color on hover */

.btn-group button:hover {

  background-color: #3e8e41;

}


/*mobile menu*/

.mobile-container {

  max-width: 480px;

  margin: auto;

  background-color: #555;

  height: 500px;

  color: white;

  border-radius: 10px;

}


.topnav {

  overflow: hidden;

  background-color: #333;

  position: relative;

}


.topnav #myLinks {

  display: none;

}


.topnav a {

  color: white;

  padding: 14px 16px;

  text-decoration: none;

  font-size: 17px;

  display: block;

}


.topnav a.icon {

  background: black;

  display: block;

  position: absolute;

  right: 0;

  top: 0;

}


.topnav a:hover {

  background-color: #ddd;

  color: black;

}


.active {

  background-color: #04AA6D;

  color: white;

}

</style>

</head>

<body>


<div class="slideshow-container">


<!-- Top Navigation Menu -->

<div class="topnav">

  <a href="#home" class="active">Radiant Systems</a>

  <div id="myLinks">

    <a href="#news">News</a>

    <a href="#contact">Contact</a>

    <a href="#about">About</a>

  </div>

  <a href="javascript:void(0);" class="icon" onclick="myFunction()">

    <i class="fa fa-bars"></i>

  </a>

</div>


<div class="mySlides fade">

  <img src="img_nature_wide.jpg" style="width:100%"> 

  <div>Slide 1</div>

  <div style="text-align:center"><br/>

  <div class="btn-group">

  <button>Contact</button>

  </div>

   </div>   

</div>


<div class="mySlides fade">

  

  <img src="img_snow_wide.jpg" style="width:100%">

  <div>Slide 2</div>

  <div style="text-align:center"><br/>

  <div class="btn-group">

  <button>Contact</button>

  </div>

   </div>  

</div>


<div class="mySlides fade">

   

  <img src="img_mountains_wide.jpg" style="width:100%">

 <div>Slide 3</div>

  <div style="text-align:center"><br/>

  <div class="btn-group">

  <button>Contact</button>

  </div>

   </div>  

</div>


<a class="prev" onclick="plusSlides(-1)">❮</a>

<a class="next" onclick="plusSlides(1)">❯</a>


</div>

<br>


<div style="text-align:center">

  <span class="dot" onclick="currentSlide(1)"></span> 

  <span class="dot" onclick="currentSlide(2)"></span> 

  <span class="dot" onclick="currentSlide(3)"></span> 

</div>


<script>


function myFunction() {

  var x = document.getElementById("myLinks");

  if (x.style.display === "block") {

    x.style.display = "none";

  } else {

    x.style.display = "block";

  }

}



let slideIndex = 1;

showSlides(slideIndex);


function plusSlides(n) {

  showSlides(slideIndex += n);

}


function currentSlide(n) {

  showSlides(slideIndex = n);

}


function showSlides(n) {

  let i;

  let slides = document.getElementsByClassName("mySlides");

  let dots = document.getElementsByClassName("dot");

  if (n > slides.length) {slideIndex = 1}    

  if (n < 1) {slideIndex = slides.length}

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

    slides[i].style.display = "none";  

  }

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

    dots[i].className = dots[i].className.replace(" active", "");

  }

  slides[slideIndex-1].style.display = "block";  

  dots[slideIndex-1].className += " active";

}

</script>


</body>

</html> 


Thursday, 23 January 2025

Angular - Interview Questions and Answers

 Angular


Module-> component -> 


npm install -g typescript

tsc -variable


npm install -g @angular/cli


ng serve --open

ng new 

ng generate component login

@input -- parent to child component

@output -- child to parent component


@input('name')

variable declaration;


Component :

Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment.


Templates - A template combines HTML with Angular markup that can modify HTML elements before they are displayed.

Template directives provide program logic, and binding markup connects your application data and the DOM.


Binding

-> One way binding

-> Two way binding - achieved by ngModel --> FormsModule --> @angular/forms

---->1. Event binding

=> String Interpolation with Attribute binding - 

---->2.Attribute binding --> [src] 

---->3.Property binding --> Binding with html elements properties <h1 [innerText]="text">

Property binding with safe navigation Operater --> ? is a safenavigation operation for null check. --> user?.name

==============

-->What are decorators in Angular? 

Decorators are a design pattern or function that defines how Angular features work. They are used to make prior modifications to a class, service, or filter. Angular supports four types of decorators, they are: Class Decorators, Property Decorators, Method Decorators and Parameter Decorators

==============

->Directives : Directives are attributes that allow the user to write new HTML syntax specific to their applications. They execute whenever the Angular compiler finds them in the DOM. Angular supports three types of directives.

1.Component directives - These are special directives that have a template or template URLs. They are essentially components that show something in the DOM.

2.Structural directives -  ngFor, ngIf - These directives manipulate the DOM elements by adding or removing elements, thus changing the structure of the DOM. ngFor Variables (index, first, last, even, odd)

3.Attribute directives - ngClass, ngStyle. These directives change the appearance or behavior of an html element.

    

Creating Custom Directive - Highlighting Text Example, you can use the @Directive  

- ng generate directive highlight(directive name) 

================

->Pipes: - 

change one value to another value

Some key features include:

Pipes are defined using the pipe “|” symbol.

Pipes can be chained with other pipes.

Pipes can be provided with arguments by using the colon (:) sign.

--> pripe ice ppercase pipe,lowercase pipes, slice pipe

Date pipe - > unformated date to fourmatted date . {{toDate | date}} 

===============================================

->LifeCycle Hooks

1.Constructor: Angular invokes the component class constructor

2.ngOnChanges: --only for @input decorator-- Angular calls ngOnChanges method whenever it detects changes to input properties. The first call happens before the component is fully initialized, which is before ngOnInit

3.ngOnInit: It gets called once, after the first ngOnChanges. At this point, the component is fully initialized

4.ngDoCheck: Angular calls ngDoCheck method immediately after ngOnInit and then every subsequent check of the component

5.ngAfterContentInit and ngAfterContentChecked: are called after Angular projects external content into the component's view

6.ngAfterViewInit and ngAfterViewChecked: These are called when the component's view, and the views of its child directives, are fully initialized


==========================================



Monday, 15 February 2021

Java 8 Features

Some of the important Java 8 features are;

  1. forEach() method in Iterable interface
  2. default and static methods in Interfaces
  3. Functional Interfaces and Lambda Expressions
  4. Java Stream API for Bulk Data Operations on Collections
  5. Java Time API
  6. Collection API improvements
  7. Concurrency API improvements
  8. Java IO improvements
  9. Miscellaneous Core API improvements
  1. forEach() method in Iterable interface

    Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if iterator is not used properly.

    Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse. Let’s see forEach usage with simple example.

    package com.journaldev.java8.foreach;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.function.Consumer;
    import java.lang.Integer;
    
    public class Java8ForEachExample {
    
    	public static void main(String[] args) {
    		
    		//creating sample Collection
    		List<Integer> myList = new ArrayList<Integer>();
    		for(int i=0; i<10; i++) myList.add(i);
    		
    		//traversing using Iterator
    		Iterator<Integer> it = myList.iterator();
    		while(it.hasNext()){
    			Integer i = it.next();
    			System.out.println("Iterator Value::"+i);
    		}
    		
    		//traversing through forEach method of Iterable with anonymous class
    		myList.forEach(new Consumer<Integer>() {
    
    			public void accept(Integer t) {
    				System.out.println("forEach anonymous class Value::"+t);
    			}
    
    		});
    		
    		//traversing with Consumer interface implementation
    		MyConsumer action = new MyConsumer();
    		myList.forEach(action);
    		
    	}
    
    }
    
    //Consumer implementation that can be reused
    class MyConsumer implements Consumer<Integer>{
    
    	public void accept(Integer t) {
    		System.out.println("Consumer impl Value::"+t);
    	}
    
    
    }
    

    The number of lines might increase but forEach method helps in having the logic for iteration and business logic at separate place resulting in higher separation of concern and cleaner code.

  2. default and static methods in Interfaces

    If you read forEach method details carefully, you will notice that it’s defined in Iterable interface but we know that interfaces can’t have method body. From Java 8, interfaces are enhanced to have method with implementation. We can use default and static keyword to create interfaces with method implementation. forEach method implementation in Iterable interface is:

    	default void forEach(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : this) {
                action.accept(t);
            }
        }
    

    We know that Java doesn’t provide multiple inheritance in Classes because it leads to Diamond Problem. So how it will be handled with interfaces now, since interfaces are now similar to abstract classes. The solution is that compiler will throw exception in this scenario and we will have to provide implementation logic in the class implementing the interfaces.

    package com.journaldev.java8.defaultmethod;
    
    @FunctionalInterface
    public interface Interface1 {
    
    	void method1(String str);
    	
    	default void log(String str){
    		System.out.println("I1 logging::"+str);
    	}
    	
    	static void print(String str){
    		System.out.println("Printing "+str);
    	}
    	
    	//trying to override Object method gives compile-time error as
    	//"A default method cannot override a method from java.lang.Object"
    	
    //	default String toString(){
    //		return "i1";
    //	}
    	
    }
    
    package com.journaldev.java8.defaultmethod;
    
    @FunctionalInterface
    public interface Interface2 {
    
    	void method2();
    	
    	default void log(String str){
    		System.out.println("I2 logging::"+str);
    	}
    
    }
    

    Notice that both the interfaces have a common method log() with implementation logic.

    package com.journaldev.java8.defaultmethod;
    
    public class MyClass implements Interface1, Interface2 {
    
    	@Override
    	public void method2() {
    	}
    
    	@Override
    	public void method1(String str) {
    	}
    
    	//MyClass won't compile without having it's own log() implementation
    	@Override
    	public void log(String str){
    		System.out.println("MyClass logging::"+str);
    		Interface1.print("abc");
    	}
    	
    }
    

    As you can see that Interface1 has static method implementation that is used in MyClass.log() method implementation. Java 8 uses default and static methods heavily in Collection API and default methods are added so that our code remains backward compatible.

    If any class in the hierarchy has a method with the same signature, then default methods become irrelevant. Since any class implementing an interface already has Object as a superclass, if we have equals(), hashCode() default methods in the interface, it will become irrelevant. That’s why for better clarity, interfaces are not allowed to have Object default methods.

    For complete details of interface changes in Java 8, please read Java 8 interface changes.

  3. Functional Interfaces and Lambda Expressions

    If you notice above interfaces code, you will notice @FunctionalInterface annotation. Functional interfaces are new concept introduced in Java 8. An interface with exactly one abstract method becomes Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. You can think of it like @Override annotation and it’s best practice to use it. java.lang.Runnable with single abstract method run() is a great example of functional interface.

    One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them. We can instantiate an interface with anonymous class but the code looks bulky.

    Runnable r = new Runnable(){
    			@Override
    			public void run() {
    				System.out.println("My Runnable");
    			}};
    

    Since functional interfaces have only one method, lambda expressions can easily provide the method implementation. We just need to provide method arguments and business logic. For example, we can write above implementation using lambda expression as:

    Runnable r1 = () -> {
    			System.out.println("My Runnable");
    		};
    

    If you have single statement in method implementation, we don’t need curly braces also. For example above Interface1 anonymous class can be instantiated using lambda as follows:

    Interface1 i1 = (s) -> System.out.println(s);
    		
    i1.method1("abc");
    

    So lambda expressions are a means to create anonymous classes of functional interfaces easily. There are no runtime benefits of using lambda expressions, so I will use it cautiously because I don’t mind writing a few extra lines of code.

    A new package java.util.function has been added with bunch of functional interfaces to provide target types for lambda expressions and method references. Lambda expressions are a huge topic, I will write a separate article on that in the future.

    You can read complete tutorial at Java 8 Lambda Expressions Tutorial.

  4. Java Stream API for Bulk Data Operations on Collections

    A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution. This is one of the best features for me because I work a lot with Collections and usually with Big Data, we need to filter out them based on some conditions.

    Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for sequential and parallel execution. Let’s see their usage with simple example.

    package com.journaldev.java8.stream;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Stream;
    
    public class StreamExample {
    
    	public static void main(String[] args) {
    		
    		List<Integer> myList = new ArrayList<>();
    		for(int i=0; i<100; i++) myList.add(i);
    		
    		//sequential stream
    		Stream<Integer> sequentialStream = myList.stream();
    		
    		//parallel stream
    		Stream<Integer> parallelStream = myList.parallelStream();
    		
    		//using lambda with Stream API, filter example
    		Stream<Integer> highNums = parallelStream.filter(p -> p > 90);
    		//using lambda in forEach
    		highNums.forEach(p -> System.out.println("High Nums parallel="+p));
    		
    		Stream<Integer> highNumsSeq = sequentialStream.filter(p -> p > 90);
    		highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p));
    
    	}
    
    }
    

    If you will run above example code, you will get output like this:

    High Nums parallel=91
    High Nums parallel=96
    High Nums parallel=93
    High Nums parallel=98
    High Nums parallel=94
    High Nums parallel=95
    High Nums parallel=97
    High Nums parallel=92
    High Nums parallel=99
    High Nums sequential=91
    High Nums sequential=92
    High Nums sequential=93
    High Nums sequential=94
    High Nums sequential=95
    High Nums sequential=96
    High Nums sequential=97
    High Nums sequential=98
    High Nums sequential=99
    

    Notice that parallel processing values are not in order, so parallel processing will be very helpful while working with huge collections.
    Covering everything about Stream API is not possible in this post, you can read everything about Stream API at Java 8 Stream API Example Tutorial.

  5. Java Time API

    It has always been hard to work with Date, Time and Time Zones in java. There was no standard approach or API in java for date and time in Java. One of the nice addition in Java 8 is the java.time package that will streamline the process of working with time in java.

    Just by looking at Java Time API packages, I can sense that it will be very easy to use. It has some sub-packages java.time.format that provides classes to print and parse dates and times and java.time.zone provides support for time-zones and their rules.

    The new Time API prefers enums over integer constants for months and days of the week. One of the useful class is DateTimeFormatter for converting DateTime objects to strings.

    For complete tutorial, head over to Java Date Time API Example Tutorial.

  6. Collection API improvements

    We have already seen forEach() method and Stream API for collections. Some new methods added in Collection API are:

    • Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaining element until all elements have been processed or the action throws an exception.
    • Collection default method removeIf(Predicate filter) to remove all of the elements of this collection that satisfy the given predicate.
    • Collection spliterator() method returning Spliterator instance that can be used to traverse elements sequentially or parallel.
    • Map replaceAll()compute()merge() methods.
    • Performance Improvement for HashMap class with Key Collisions
  7. Concurrency API improvements

    Some important concurrent API enhancements are:

    • ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
    • CompletableFuture that may be explicitly completed (setting its value and status).
    • Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.
  8. Java IO improvements

    Some IO improvements known to me are:

    • Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
    • Files.lines(Path path) that reads all lines from a file as a Stream.
    • Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
    • BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.
  9. Miscellaneous Core API improvements

    Some misc API improvements that might come handy are:

    1. ThreadLocal static method withInitial(Supplier supplier) to create instance easily.
    2. Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
    3. min(), max() and sum() methods in Integer, Long and Double wrapper classes.
    4. logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
    5. ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
    6. Several utility methods in Math class.
    7. jjs command is added to invoke Nashorn Engine.
    8. jdeps command is added to analyze class files
    9. JDBC-ODBC Bridge has been removed.
    10. PermGen memory space has been removed

That’s all for Java 8 features with example programs. If I have missed some important features of Java 8, please let me know through comments.

Saturday, 13 February 2021

What is hashCode?

The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data structure. We know that hash code is a unique id number allocated to an object by JVM. But actually speaking, Hash code is not an unique number for an object. If two objects are equals then these two objects should return the same hash code. So we have to implement hashcode() method of a class in such way that if two objects are equals, ie compared by equal() method of that class, then those two objects must return same hash code. If you are overriding hashCode you need to override equals method also.

What is the difference between Hashtable and HashMap?

Answer:
The basic differences are Hashtable is synchronized and HashMap is not synchronized. Hashtable does not allow null values, and HashMap allows null values.

What is the difference between ArrayList and LinkedList?

Answer:

Both ArrayList and LinkedList are implementation of List interface in Java. Both classes are non-synchronized. But there are certain differences as well.

Following are the important differences between ArrayList and LinkedList method.

Sr. No.
Key
ArrayList
LinkedList
1
Internal Implementation
ArrayList internally uses a dynamic array to store its elements.
LinkedList uses Doubly Linked List to store its elements.
2
Manipulation
ArrayList is slow as array manipulation is slower.
LinkedList is faster being node based as not much bit shifting required.
3
Implementation
ArrayList implements only List.
LinkedList implements List as well as Queue. It can acts as a queue as well.
4
Access
ArrayList is faster in storing and accessing data.
LinkedList is faster in manipulation of data.