An open API service indexing awesome lists of open source software.

https://github.com/code-flu/java-stream-api-questions-with-solution

Java Stream API Questions with Solution
https://github.com/code-flu/java-stream-api-questions-with-solution

Last synced: 10 days ago
JSON representation

Java Stream API Questions with Solution

Awesome Lists containing this project

README

          

# Java Stream API Questions with Solution

- [String Questions](#string-questions)
- [Integer Questions](#integer-questions)

## String Questions

Count total number of characters in a string

```java
public static void main(String[] args)
{
String str = "hello world";

long count = str.chars().count();

System.out.println(count);
}
```

Convert the entire string to uppercase

```java
public static void main(String[] args)
{
String str = "hello world";

String upperCaseStr = str.chars()
.mapToObj(Character::toString)
.map(String::toUpperCase)
.collect(Collectors.joining());

System.out.println(upperCaseStr);
}
```

Convert the entire string to lowercase

```java
public static void main(String[] args)
{
String str = "HELLO WORLD";

String lowerCaseStr = str.chars()
.mapToObj(Character::toString)
.map(String::toLowerCase)
.collect(Collectors.joining());

System.out.println(lowerCaseStr);
}
```

Count the number of occurrences of a specific character (e.g., 'l')

#### solution-1

```java
public static void main(String[] args)
{
String str = "Hello Lost World";

long count = str.chars()
.filter(ch -> ch == 'L' || ch == 'l')
.count();

System.out.println(count);
}
```

#### solution-2

```java
public static void main(String[] args)
{
String str = "Hello Lost World";

long count = str.chars()
.mapToObj(Character::toLowerCase)
.filter(ch -> ch == 'l')
.count();

System.out.println(count);
}
```

Reverse the order of the characters in the string

#### solution-1

```java
public static void main(String[] args)
{
String str = "hello world";

String reverseStr = str.chars()
.mapToObj(Character::toString)
.reduce((str1, str2) -> str2 + str1)
.orElseThrow();

System.out.println(reverseStr);
}
```

#### solution-2

```java
public static void main(String[] args)
{
String str = "hello world";

String reverseStr = IntStream.range(0, str.length())
.mapToObj(i -> String.valueOf(str.charAt(str.length() - i - 1)))
.collect(Collectors.joining());

System.out.println(reverseStr);
}
```

Reverse the order of the words in the string

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String newStr = Arrays.stream(str.split("\\s+"))
.reduce((string, string2) -> string2 + " " + string)
.orElseThrow();

System.out.println(newStr);
}
```

Reverse the characters of each word in a given string while keeping the order of words intact

```java
public static void main(String[] args)
{
String str = "hello world";

String newStr = Stream.of(str.split("\\s+"))
.map(val -> new StringBuilder(val).reverse())
.collect(Collectors.joining(" "));

System.out.println(newStr);
}
```

Replace all occurrences of a specific word with another word

```java
public static void main(String[] args)
{
String str = "Banana is tasty, but some people prefer Banana pie.";

String newStr = Stream.of(str.split("\\s+"))
.map(val -> val.equalsIgnoreCase("Banana") ? "Apple" : val)
.collect(Collectors.joining(" "));

System.out.println(newStr);
}
```

Capitalize the first character of each word in the string

```java
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy dog";

String newStr = Stream.of(str.split("\\s+"))
.map(val -> Character.toUpperCase(val.charAt(0)) + val.substring(1))
.collect(Collectors.joining(" "));

System.out.println(newStr);
}
```

Remove all non-alphabetic characters from a string

```java
public static void main(String[] args)
{
String str = "Th3 qu!ck br0wn f0x jump$ 0ver the l4zy d0g";

String sanitizeStr = str.chars()
.filter(Character::isLetter)
.mapToObj(Character::toString)
.collect(Collectors.joining());

System.out.println(sanitizeStr);
}
```

Extract all the unique characters from the string

```java
public static void main(String[] args)
{
String str = "hello world";

String newStr = str.chars()
.mapToObj(Character::toString)
.distinct().collect(Collectors.joining());

System.out.println(newStr);
}
```

Filter out all the vowels from the string

```java
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy dog";
String vowels = "aeiou";

String newStr = str.chars()
.mapToObj(Character::toString)
.filter(val -> !vowels.contains(val))
.collect(Collectors.joining());

System.out.println(newStr);
}
```

Find the first non-repeating character in the string

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String newStr = str.chars()
.mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst().orElseThrow();

System.out.println(newStr);
}
```

Find the all non-repeating characters in the string

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

List map = str.chars()
.mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());

System.out.println(map);
}
```

Group characters by their frequency of occurrence

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

Map map = str.chars()
.mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(map);
}
```

count the occurrences of each character and then sorts these characters based on their counts in ascending order

#### solution-1
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

Map map = str.chars()
.mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

System.out.println(map);
}
```

#### solution-2
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

Map map = new LinkedHashMap<>();
str.chars()
.mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(entry -> map.put(entry.getKey(), entry.getValue()));

System.out.println(map);
}
```

Split the string into an array of words

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String[] arr = Arrays.stream(str.split("\\s+"))
.toArray(String[]::new);

System.out.println(Arrays.toString(arr));
}
```

Sort the words in the string alphabetically (ascending or descending)

#### ascending
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String[] arr = Arrays.stream(str.split("\\s+"))
.sorted()
.toArray(String[]::new);

System.out.println(Arrays.toString(arr));
}
```

#### descending
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String[] arr = Arrays.stream(str.split("\\s+"))
.sorted(Comparator.reverseOrder())
.toArray(String[]::new);

System.out.println(Arrays.toString(arr));
}
```

Filter out words with a specific length (e.g., only words with 5 letters)

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

String[] arr = Arrays.stream(str.split("\\s+"))
.filter(val -> val.length() == 5)
.toArray(String[]::new);

System.out.println(Arrays.toString(arr));
}
```

Find the longest or shortest word in the string

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over a lazy dog";

String longestWord = Arrays.stream(str.split("\\s+"))
.max(Comparator.comparing(String::length)).orElseThrow();

String shortestWord = Arrays.stream(str.split("\\s+"))
.min(Comparator.comparing(String::length)).orElseThrow();

System.out.println(longestWord);
System.out.println(shortestWord);
}
```

Join all the words in the string with a specific delimiter (e.g., "-")

#### solution-1
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over a lazy dog";

String newStr = Arrays.stream(str.split("\\s+"))
.collect(Collectors.joining("-"));

System.out.println(newStr);
}
```

#### solution-2
```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over a lazy dog";

String newStr = Arrays.stream(str.split("\\s+"))
.reduce((string, string2) -> string + "-" + string2)
.orElseThrow();

System.out.println(newStr);
}
```

Print only the even-indexed characters in uppercase

```java
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy dog";

String newStr = IntStream.range(0, str.length())
.filter(i -> i % 2 == 0)
.mapToObj(str::charAt)
.map(Character::toUpperCase)
.map(String::valueOf)
.collect(Collectors.joining());

System.out.println(newStr);
}
```

Check if a string is a palindrome

#### solution-1
```java
public static void main(String[] args)
{
String str = "level";

boolean isPalindrome = str.chars()
.mapToObj(Character::toString)
.reduce((val, val2) -> val2 + val)
.orElseThrow().equals(str);

System.out.println(isPalindrome);
}
```

#### solution-2
```java
public static void main(String[] args)
{
String str = "level";

boolean isPalindrome = IntStream.range(0, str.length() / 2)
.noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));

System.out.println(isPalindrome);
}
```

Find all the substrings of a specific length (e.g., all 3-letter substrings)

```java
public static void main(String[] args)
{
String str = "hellWorld";
int subStrLength = 3;

IntStream.range(0, str.length() - subStrLength + 1)
.mapToObj(i -> str.substring(i, subStrLength + i))
.forEach(System.out::println);
}
```

Map each character of "hello world" to its uppercase version

```java
public static void main(String[] args)
{
String str = "helloWorld";

Map map = str.chars()
.mapToObj(Character::toString)
.collect(Collectors.toMap(
Function.identity(),
String::toUpperCase,
(string, string2) -> string2 // Merge function to handle duplicates (keep the first occurrence)
));

System.out.println(map);
}
```

Calculate the average length of each word in the string

```java
public static void main(String[] args)
{
String str = "the quick brown fox jumps over the lazy dog";

System.out.println(Stream.of(str.split("\\s+"))
.collect(Collectors.averagingInt(String::length)));
}
```

## Integer Questions

Find the count/sum/average/minimum/maximum of integers

### solution-1

```java
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

long count = Arrays.stream(arr).count();
int sum = Arrays.stream(arr).sum();
double average = Arrays.stream(arr).average().orElseThrow();
int max = Arrays.stream(arr).max().orElseThrow();
int min = Arrays.stream(arr).min().orElseThrow();

System.out.println(count);
System.out.println(sum);
System.out.println(average);
System.out.println(max);
System.out.println(min);
}
```

### solution-2

```java
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

long count = IntStream.of(arr).count();
int sum = IntStream.of(arr).sum();
double average = IntStream.of(arr).average().orElseThrow();
int max = IntStream.of(arr).max().orElseThrow();
int min = IntStream.of(arr).min().orElseThrow();

System.out.println(count);
System.out.println(sum);
System.out.println(average);
System.out.println(max);
System.out.println(min);
}
```

Filter out even/odd numbers from the array

```java
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int[] even = Arrays.stream(arr)
.filter(val -> val % 2 == 0)
.toArray();

int[] odd = Arrays.stream(arr)
.filter(val -> val % 2 != 0)
.toArray();

System.out.println(Arrays.toString(even));
System.out.println(Arrays.toString(odd));
}
```

Create a new array with the square of each element

```java
public static void main(String[] args)
{
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int[] squareArr = Arrays.stream(arr)
.map(val -> val * val)
.toArray();

System.out.println(Arrays.toString(squareArr));
}
```

Filter elements greater than a specific value (e.g., greater than 5)

```java
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int[] filteredArr = Arrays.stream(arr)
.filter(val -> val > 5)
.toArray();

System.out.println(Arrays.toString(filteredArr));
}
```

Find the product of all elements in the array

```java
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

int product = Arrays.stream(arr)
.reduce((left, right) -> left * right)
.orElseThrow();

System.out.println(product);
}
```

Sort the array in ascending order

```java
public static void main(String[] args)
{
int[] arr = {2, 9, 4, 3, 6, 8, 1, 7};

int[] sortedArr = Arrays.stream(arr)
.sorted().toArray();

System.out.println(Arrays.toString(sortedArr));
}
```

Sort the array in descending order

```java
public static void main(String[] args)
{
int[] arr = {2, 9, 4, 3, 6, 8, 1, 7};

Integer[] sortedArr = Arrays.stream(arr)
.boxed()
.sorted(Comparator.reverseOrder())
.toArray(Integer[]::new);

System.out.println(Arrays.toString(sortedArr));
}
```

Get all the elements in the array that are unique (remove duplicates)

```java
public static void main(String[] args)
{
int[] arr = {2, 9, 2, 3, 3, 8, 1, 7};

int[] sortedArr = Arrays.stream(arr)
.distinct()
.toArray();

System.out.println(Arrays.toString(sortedArr));
}
```

Array of duplicate elements

### solution-1
```java
public static void main(String[] args)
{
int[] arr = {9, 9, 2, 3, 3, 8, 1, 2};

int[] duplArr = Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.mapToInt(Map.Entry::getKey)
.toArray();

System.out.println(Arrays.toString(duplArr));
}
```

### solution-2
```java
public static void main(String[] args)
{
int[] arr = {9, 9, 2, 3, 3, 8, 1, 2};

Set set = new HashSet<>();

int[] duplArr = Arrays.stream(arr)
.filter(val -> !set.add(val))
.toArray();

System.out.println(Arrays.toString(duplArr));
}
```

Partition the array into two lists: one with even numbers and another with odd numbers

```java
public static void main(String[] args)
{
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7};

Map> evenAndOdd = Arrays.stream(arr)
.boxed()
.collect(Collectors.partitioningBy(val -> val % 2 == 0));

List evenLists = evenAndOdd.get(true);
List oddLists = evenAndOdd.get(false);

System.out.println(evenLists);
System.out.println(oddLists);
}
```

Group elements by their remainder when divided by 3?

```java
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Map> map = Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(val -> val % 3));

System.out.println(map);
}
```

Group each element with their remainder when divided by 3?

```java
public static void main(String[] args)
{
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Map map = Arrays.stream(arr)
.boxed()
.collect(Collectors.toMap(Function.identity(), val -> val % 3));

System.out.println(map);
}
```

Calculate sum of numeric values in a string

```java
public static void main(String[] args)
{
String str = "38457";

int sum = str
.chars()
.mapToObj(Character::getNumericValue)
.mapToInt(Integer::intValue).sum();

System.out.println(sum);
}
```