Interview Questions
Java
java Advanced Interview questions
Java Certification
Java Concurrent Tutorials
Java Freshers Interview Questions
Java interview questions
Java Interview Questions
Java Interview Questions
Java8 Examples
java8 streams examples
Java8 Realtime Examples-Filter,map
1. Grouping a list of articles by their category and then sorting them by their title:
List<Article> articles = ...;
Map<String, List<Article>> articlesByCategory = articles.stream()
.collect(Collectors.groupingBy(Article::getCategory));
articlesByCategory.forEach((category, articles) -> {
articles.sort(Comparator.comparing(Article::getTitle));
System.out.println("Category: " + category);
articles.forEach(System.out::println);
});
2. Finding the most frequent element in a list of log entries:
List<LogEntry> logEntries = ...;
Optional<LogEntry> mostFrequent = logEntries.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey);
3. Summing up the total Salary of a list of Employees:
List<Employee> employees= ...;
double totalSalary = employess.stream()
.mapToDouble(Employee::getSalary)
.sum();
4. Filtering and transforming a list of customer data
List<Customer> customers = ...;
List<String> activeCustomerEmails = customers.stream()
.filter(c -> c.isActive())
.map(c -> c.getEmail())
.collect(Collectors.toList());
5. Parsing a large CSV file and processing the data in parallel:
try (Stream<String> lines = Files.lines(Paths.get("large-file.csv"))) {
lines.parallel()
.map(line -> line.split(","))
.filter(values -> values.length == 3)
.map(values -> new DataRecord(values[0], values[1], values[2]))
.forEach(dataRecord -> processData(dataRecord));
}
6.Finding the most common word in a large text file:
try (Stream<String> lines = Files.lines(Paths.get("large-file.txt"))) {
Map<String, Long> wordCounts = lines.flatMap(line -> Arrays.stream(line.split(" ")))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Optional<Map.Entry<String, Long>> mostCommonWord = wordCounts.entrySet().stream()
.max(Map.Entry.comparingByValue());
System.out.println("Most common word: " + mostCommonWord.get().getKey());
}
7. Java8 Streams Filtering a large dataset based on multiple conditions:
List<Record> records = ...;
List<Record> filteredRecords = records.stream()
.filter(record -> record.getAge() > 25)
.filter(record -> record.getIncome() > 50000)
.filter(record -> record.getGender().equals("M"))
.collect(Collectors.toList());