Java 8 Interview Programs
Find the first non-repeating character in a String using Java 8
javabestinterviewquestion.blogspot.com
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String input = "programming";
Character result = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println(result);
}
}
Find duplicate elements in a list using Stream
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 3, 5);
Set<Integer> duplicates = numbers.stream()
.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(duplicates);
}
}
3. Sort a list of employees by salary (ascending and descending)
class Employee {
String name;
int salary;
// constructor, getters
}
List<Employee> employees = // initialize list
// Ascending
employees.stream()
.sorted(Comparator.comparing(Employee::getSalary))
.forEach(System.out::println);
// Descending
employees.stream()
.sorted(Comparator.comparing(Employee::getSalary).reversed())
.forEach(System.out::println);
4. Group employees by department
Map<String, List<Employee>> groupedByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
5. Find max salary employee
Employee highestPaid = employees.stream()
.max(Comparator.comparing(Employee::getSalary))
.orElse(null);
6. Convert List<String> to List<Integer> (e.g., parsing numbers)
List<String> strNums = Arrays.asList("1", "2", "3");
List<Integer> nums = strNums.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
7. Count frequency of each character in a String
String input = "banana";
Map<Character, Long> freq = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
8. Use Optional to avoid null pointer
Optional<String> name = Optional.ofNullable(getName());
System.out.println(name.orElse("Default"));
9. Sum of all even numbers in a list
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
10. Flatten a List of List using flatMap()
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("A", "B"),
Arrays.asList("C", "D")
);
List<String> flatList = nestedList.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
1. Reverse Each Word in a Sentence Input: "Java 8 Stream API" Output: "avaJ 8 maertS IPA" String sentence = "Java 8 Stream API"; String result = Arrays.stream(sentence.split(" ")) .map(word -> new StringBuilder(word).reverse().toString()) .collect(Collectors.joining(" ")); System.out.println(result); 2. Find the Most Repeated Word in a Sentence Input: "apple banana apple orange banana apple" Output: apple String input = "apple banana apple orange banana apple"; String mostRepeated = Arrays.stream(input.split(" ")) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); System.out.println(mostRepeated); 3. Find Numbers Starting with '1' Input: [10, 15, 25, 30, 11] Output: [10, 15, 11] List<Integer> numbers = Arrays.asList(10, 15, 25, 30, 11); List<Integer> result = numbers.stream() .map(String::valueOf) .filter(s -> s.startsWith("1")) .map(Integer::valueOf) .collect(Collectors.toList()); System.out.println(result); 4. Sort Map by Value in Descending Order Map<String, Integer> map = Map.of("apple", 3, "banana", 5, "orange", 2); map.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue())); 5. Remove Duplicate Characters from a String Input: "banana" Output: "ban" String input = "banana"; String result = input.chars() .mapToObj(c -> String.valueOf((char) c)) .distinct() .collect(Collectors.joining()); System.out.println(result); 6. Group Words by Their Length List<String> words = List.of("apple", "bat", "banana", "ant", "cherry"); Map<Integer, List<String>> grouped = words.stream() .collect(Collectors.groupingBy(String::length)); System.out.println(grouped); 7. Sum of Digits of All Numbers in a List Input: [12, 34, 56] Output: 1+2+3+4+5+6 = 21 List<Integer> list = Arrays.asList(12, 34, 56); int sum = list.stream() .map(String::valueOf) .flatMapToInt(str -> str.chars().map(Character::getNumericValue)) .sum(); System.out.println(sum); 8. Convert List of Employees to Map (id -> name) Map<Integer, String> empMap = employees.stream() .collect(Collectors.toMap(Employee::getId, Employee::getName)); 9. Partition Even and Odd Numbers Map<Boolean, List<Integer>> partitioned = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0)); System.out.println("Even: " + partitioned.get(true)); System.out.println("Odd: " + partitioned.get(false)); 10. Chained Filter + Map + Collect Input: List of strings, filter non-empty, convert to uppercase, collect** List<String> words = Arrays.asList("java", "", "stream", "api", ""); List<String> result = words.stream() .filter(s -> !s.isEmpty()) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(result); // [JAVA, STREAM, API]