26 Java 8 Programs using Lambda Expression and Stream
Categories: Java 8(JDK1.8) Java Java Examples
26 Java 8 Programs using Lambda Expression and Stream
- Write a program to append char in char ex-input- {A, B, C} output->[A_X, B_Y, C_Z]
- Write a Java 8 program to calculate the age of a person in years given their birthday
- How to check if list is empty in Java 8 using Optional.if not null, iterate through the list and print the object
- Count of each character in a String using Java 8
- How to count the number of occurrences of a given word in a list of strings using Java 8
- Write a Java program To create a map from an array of strings where the key is the string and the value is its length
- Drop all while conditions not meet
- Duplicate elements with its count using Java 8
- How to filter and collect a list/array of strings that start with a specific letter using Java 8 Stream
- How to filter an array of strings by a given prefix using Java 8 Stream
- How to find next/previous(tomorrow/yesterday) date using Java 8?
- Write a Java 8 program to print the first 10 odd numbers
- Write a program for group words by first character of given string
- How to increment salary of Employee by 2%, 5% etc using java 8
- How to iterate and modify values in a Map using Java 8
- Find Last duplicate character of given string using Java 8
- Write a Java 8 program to get the last element of an array string/object
- How to print keys & values of a Map using Java 8
- Write a Program to find the Maximum element in an array using Java 8
- Find the maximum value in a list of integers using Stream & Method Reference using Java 8
- Write a program to find the only duplicate count list in the List using java 8
- How to remove all duplicates from an array of integers in Java using Java 8
- Given a list of integers, separate odd and even numbers
- How to sort a list of strings by length using Lambda expressions using Java 8
- Write a program to sum an array using Java 8
- Write a program to sum an array without using the sum method using Java 8
Java 8 Program 1:- Write a program to append char in char ex-input- {A, B, C} output->[A_X, B_Y, C_Z]
package r4r.co.in;
import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
public class AppendCharInCharExIinput { //Write a program to append char in char ex-input- {A, B, C} output->[A_X, B_Y, C_Z] public static void main(String[] args) { Character[] input = { 'A', 'B', 'C' }; List<String> list = Stream.of(input).map(c -> c + "_" + (char) (c + 23)).collect(Collectors.toList()); System.out.println(list); } } |
Java 8 Program 2:- Write a Java 8 program to calculate the age of a person in years given their birthday
package r4r.co.in;
import java.time.LocalDate; import java.time.Period; import java.time.temporal.ChronoUnit;
public class CalculateAge {
public static void main(String[] args) {
//Write a Java 8 program to calculate the age of a person in years given their birthday. //Java-8 (java.time-package) LocalDate dateOfBirth = LocalDate.of(1982, 07, 21); LocalDate localDate = LocalDate.now(); //Only Years System.out.println("Your Age[Year] - " + ChronoUnit.YEARS.between(dateOfBirth, localDate)); // Years,Months,Days Period period =Period.between(dateOfBirth, localDate); System.out.println("Year:-"+period.getYears()+" Months:-"+period.getMonths()+" Days:-"+period.getDays()); } } |
Java 8 Program 3:- How to check if list is empty in Java 8 using Optional.if not null iterate through the list and print the object
package r4r.co.in;
import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional;
public class CheckListIsEmptyOrNot {
public static void main(String[] args) { //How to check if list is empty in Java 8 using Optional.if not null iterate through the list and print the object
List<String> checkList=null;//Arrays.asList("Rajesh");
List<String> list= Arrays.asList("Rajesh","Kumar"); Optional.ofNullable(checkList).orElse(list).stream().filter(Objects::nonNull).forEach(System.out::println); } } |
Java 8 Program 4:- Count of each character in a String using Java 8
package r4r.co.in;
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream;
public class CountEachCharacterInGivenString {
public static void main(String[] args) { // Count of each character in a String using Java 8
String str = "I am Rajesh Kumar"; // Map<Object, Long> mapUsingHashMap = Stream.of(str.split("")).filter(f -> !f.isBlank()).map(s -> s.toLowerCase()) .collect(Collectors.groupingBy(s -> s, HashMap::new, Collectors.counting())); System.out.println(mapUsingHashMap); Map<Object, Long> mapUsingLinkedHashMap = Stream.of(str.split("")).filter(f -> !f.isBlank()) .map(s -> s.toLowerCase()) .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting())); System.out.println(mapUsingLinkedHashMap);
Map<Object, Long> mapUsingFuntionIdentity = Stream.of(str.split("")).filter(f -> !f.isBlank()) .map(s -> s.toLowerCase()).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.print(mapUsingFuntionIdentity); } }
|
Java 8 Program 5:- How to count the number of occurrences of a given word in a list of strings using Java 8
package r4r.co.in;
import java.util.Arrays; import java.util.List;
public class CountGivenWordInGivenArryOfStringUsingJava8Lamda {
public static void main(String[] args) { // How to count the number of occurrences of a given word in a list of strings using Java 8 String[] input = { "Rajesh Kumar r4r", "Rajesh r4r Kumar r4r Rajesh", "r4r r4r" ,"Rajesh Kumar"}; List<String> list = Arrays.asList(input); //List<String> list=Arrays.asList("Rajesh Kumar r4r", "Rajesh r4r Kumar r4r Rajesh", "r4r r4r" ,"Rajesh Kumar"); String str = "r4r"; long count = list.stream().flatMap(f->Arrays.stream(f.split(" "))).filter(w -> w.equals(str)).count(); System.out.print(count); } } |
Java 8 Program 6:- Write a Java program To create a map from an array of strings where the key is the string and the value is its length
package r4r.co.in;
import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
public class CreateMapStringAsKeyAndLengthAsValue {
public static void main(String[] args) { //Write a Java program To create an map from a array of strings where the key is the string and the value is its length String[] str= {"Rajesh","Kumar"}; Map<String, Integer> map=Stream.of(str).collect(Collectors.toMap(s->s, String::length)); System.out.print(map); } }
|
Java 8 Program 7:- Drop all while condition not meet
package r4r.co.in;
import java.util.List; import java.util.Set; import java.util.stream.Collectors;
public class DropWhileExamples { //Drop all while condition not meet public static void main(String[] args) { // Unordered stream- non-deterministic Set<Long> set=Set.of(1L, 5L, 7L, 10L, 11L, 12L).stream().dropWhile(value -> value % 2 != 0).collect(Collectors.toSet()); System.out.println(set);
// Order stream List<Long> list=List.of(1L, 5L, 7L, 10L, 11L, 12L).stream().dropWhile(value -> value % 2 != 0).collect(Collectors.toList()); System.out.println(list); } }
|
Java 8 Program 8:- Duplicate elements with its count using Java 8
package r4r.co.in;
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;
public class DuplicateElementsWithItsCount {
public static void main(String[] args) { // Duplicate elements with its count using Java 8 List<String> list = Arrays.asList("1", "2", "3", "1", "2", "4");
// First Approach Map<String, Long> map = list.stream().filter(s -> Collections.frequency(list, s) > 1) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.err.println(map);
// Second Approach Map<String, Long> smap = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream() .filter(entry -> entry.getValue() > 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(smap); } } |
Java 8 Program 9:- How to filter and collect a list/array of strings that start with a specific letter using Java 8 Stream
package r4r.co.in;
import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
public class FilterBySpecificCharcter {
public static void main(String[] args) { //How to filter and collect a list/array of strings that start with a specific letter using Java 8 Stream
String[] input = { "Rajesh", "Rahul", "Verma", "Patel","R4R","r4r r4r" }; List<String> list = Stream.of(input).filter(f -> f.startsWith("R")).collect(Collectors.toList()); System.out.print(list);
} }
|
Java 8 Program 10:- How to filter an array of strings by a given prefix using Java 8 Stream
package r4r.co.in;
import java.util.Arrays; import java.util.stream.Stream;
public class FilterWithGivenPrefix {
public static void main(String[] args) { // How to filter an array of strings by a given prefix using Java 8 Stream String[] str={"Rajesh","Kumar","R4R"}; String prefix="R"; String[] filteredStr=Stream.of(str).filter(s->s.startsWith(prefix)).toArray(String[]::new); System.out.print(Arrays.toString(filteredStr)); } }
|
Java 8 Program 11:- How to find next/previous(tomorrow/yesterday) date using Java 8 ?
package r4r.co.in;
import java.time.LocalDate;
public class FindTodayTommrowYesterdayUsingJava8 {
public static void main(String[] args) { //How to find next/previous(tomorrow/yesterday) date using Java 8? LocalDate date = LocalDate.now(); System.out.println("Today :- " + date); System.out.println("Yesterday :- " + date.minusDays(1)); System.out.println("Tommorrow :- " + date.plusDays(1)); } }
|
Java 8 Program 12:- Write a Java 8 program to print the first 10 odd numbers.
package r4r.co.in;
import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
public class First10thOdd { //Write a Java 8 program to print the first 10 odd numbers public static void main(String[] args) { List<Integer> list=Stream.iterate(0,i->i+1).filter(f->f%2==0).limit(10).collect(Collectors.toList()); System.out.println(list);
List<Integer> integers=Stream.iterate(0, i->i+2).limit(10).collect(Collectors.toList()); System.out.println(integers); } } |
Java 8 Program 13:- Write a program for group words by first character of given string.
package r4r.co.in;
import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
//Write a program for group words by first character of given string public class GroupByFirstChacterGivenSring {
public static void main(String[] args) { String str = "Rajesh Kumar Verma R4r"; Map<Character, List<String>> map = Stream.of(str.split("\s")). collect(Collectors.groupingBy(s -> s.charAt(0))); System.out.print(map); } } |
Java 8 Program 14:- How to increment salary of Employee by 2%, 5% etc using java 8
package r4r.co.in;
import java.util.List; import java.util.stream.Collectors;
public class IncrementSalary {
public static void main(String[] args) { // How to increment salary of Employee by 2%, 5% etc using java 8 List<EmployeeSalary> list = List.of(new EmployeeSalary(1, "Rakesh Kumar", 32, "JUNIOR", 1100), new EmployeeSalary(2, "Rajesh Kumar", 30, "JUNIOR", 2100), new EmployeeSalary(3, "Bimal Kumar Patel", 25, "JUNIOR", 1500), new EmployeeSalary(4, "Brijesh Kumar Patel", 35, "JUNIOR", 1600));
System.out.println("Input List" + list);
//Salary increase by 2 System.out.println("Salary increase by 2 List"); List<EmployeeSalary> employeeSalaries=list.stream(). map(f->new EmployeeSalary(f.getId(), f.getName(), f.getAge(), f.getType(), f.getSalary()+(f.getSalary()*.02))).collect(Collectors.toList()); System.out.println(employeeSalaries);
// Salary increase by 5 System.out.println("Salary increase by 5 List"); List<EmployeeSalary> employeeSalaries1=list.stream().map(f->new EmployeeSalary(f.getId(), f.getName(), f.getAge(), f.getType(), f.getSalary()+(f.getSalary()*.05))).collect(Collectors.toList()); System.out.println(employeeSalaries1);
} }
class EmployeeSalary { int id; String name; int age; String type; double salary;
public EmployeeSalary(int id, String name, int age, String type, double salary) { this.id = id; this.name = name; this.age = age; this.type = type; this.salary = salary;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
@Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", type=" + type + ", age=" + age + ", salary=" + salary + "]"; } }
|
Java 8 Program 15:- How to iterate and modify values in a Map using Java 8
package r4r.co.in;
import java.util.HashMap; import java.util.Map;
public class IterateAndmodifyValuesInMapUsingJava8 {
public static void main(String[] args) { // How to iterate and modify values in a Map using Java 8 Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); map.put("2", "2"); map.put("3", "3"); map.put("4", "4"); map.put("5", "5"); map.put("6", "6"); System.out.println(map); map.computeIfPresent("1", (key, value) -> "11"); map.computeIfAbsent("7", (value) -> "7");
System.out.println("Modified Map......"); map.entrySet().forEach(System.out::println); //or //map.entrySet().iterator().forEachRemaining(System.out::println); } } |
Java 8 Program 16:- Find Last duplicate character of given string using Java 8
package r4r.co.in;
import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;
public class LastDuplicateCharacter {
public static void main(String[] args) {
// Find Last duplicate character of given string using Java 8 String str = "Rajesh Kumar is Java Lead"; Map<Character, Long> mapGroupByCharacters = str.chars().mapToObj(c -> (char) c).map(c->c.toLowerCase(c)).filter(f -> f != ' ') .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(mapGroupByCharacters);
Map<Character, Long> mapOfduplicateChacters = mapGroupByCharacters.entrySet().stream() .filter(f -> f.getValue() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(mapOfduplicateChacters);
Map<Character, Long> lastElement = mapOfduplicateChacters.entrySet().stream() .skip(mapOfduplicateChacters.size() - 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(lastElement); } } |
Java 8 Program 17:- Write a Java 8 program to get the last element of an array string/object
package r4r.co.in;
import java.util.stream.Stream;
public class LastElementOfAnArray {
public static void main(String[] args) { //Write a Java 8 program to get the last element of an array string/object String[] input = { "Rajesh", "Kumar", "Verma", "R4R" }; String lastElement = Stream.of(input).skip(input.length - 1).findAny().get(); System.out.println(lastElement); } } |
Java 8 Program 18:- How to print keys & values of a Map using Java 8.
package r4r.co.in;
import java.util.HashMap; import java.util.Map; import java.util.stream.Stream;
public class MapExamplesJava8 {
public static void main(String[] args) { // How to print keys & values of a Map using Java 8
Map<String,String> map= new HashMap<String, String>(); map.put("Key-1","value-1"); map.put("Key-2","value-2"); map.put("Key-3","value-3"); map.put("Key-4","value-4"); //using forEachRemaining //Using Java 8 – Collection.iterator() and Iterator.forEachRemaining() map.entrySet().iterator().forEachRemaining(System.out::print); //all values System.out.println("\n---------------------"); map.values().forEach(System.out::print); System.out.println("\n---------------------"); //Using Java 8 – Collection.stream() and Stream.forEach() map.entrySet().stream().forEach(System.out::print); System.out.println("\n---------------------"); //Stream -keys and values. Stream.of(map).map(m->m.keySet()).forEach(System.out::print); System.out.println("\n---------------------"); Stream.of(map).map(m->m.values()).forEach(System.out::print); System.out.println("\n---------------------"); //Using Java 8 – Stream.of() + Collection.toArray() + Stream.forEach() Stream.of(map.entrySet().toArray()).forEach(System.out::print); System.out.println("\n---------------------"); //Using Java 8 - Stream.of() and Collection.toString() and Stream.forEach() Stream.of(map.entrySet().toString()).forEach(System.out::print); } }
|
Java 8 Program 19:- Write a Program to find the Maximum element in an array using Java 8.
package r4r.co.in;
import java.util.Arrays; import java.util.Comparator;
public class MaximumOfGivenArray {
public static void main(String[] args) { //Write a Program to find the Maximum element in an array using Java 8
int[] arr= {1,2,3,4,5,66,6,7,7,4,8}; int max=Arrays.stream(arr).max().getAsInt(); System.out.println(max);
Integer[] arrInteger= {2,3,45,56,67,27,76,83,28,228,338,4343}; Integer maxValue=Arrays.stream(arrInteger).max(Comparator.naturalOrder()).get(); System.out.println(maxValue);
} } |
Java 8 Program 20:- Find the maximum value in a list of integers using Stream & Method Reference using Java 8.
package r4r.co.in;
import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Stream;
public class MaxUsingMethodReferencing { static Optional<Integer> maxValue(Stream<Integer> s) { Optional<Integer> max=s.max(Integer::compare); return max; }
public static void main(String[] args) { //Find the maximum value in a list of integers using Stream & Method Reference
List<Integer> list=Arrays.asList(1,3,4,5,6,7,77,8,8,9); int max=maxValue(list.stream()).orElse(-1); System.out.println(max);
} } |
Java 8 Program 21:- Write a program to find the only duplicate count list in the List using java 8.
package r4r.co.in;
import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;
public class OnlyDuplicateCountList {
public static void main(String[] args) { // Write a program to find the only duplicate count list in the List
List<String> list = List.of("Rajesh", "Kumar", "Verma", "Verma", "Rani", "Prisha", "Prisha", "Verma", "Rani"); Map<String, Long> map = list.stream().filter(d -> Collections.frequency(list, d) > 1) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(map); }
}
|
Java 8 Program 22:- How to remove all duplicates from an array of integers in Java using Java 8.
package r4r.co.in;
import java.util.Arrays; import java.util.stream.Stream;
public class RemoveAllDuplicateInteger {
public static void main(String[] args) { //How to remove all duplicates from an array of integers in Java using Java 8 Integer [] input= {1,2,3,6,1,9,3,7,3,7,8,3,4,5,6}; Integer[] output=Stream.of(input).distinct().toArray(Integer[]::new); System.out.print(Arrays.toString(output)); } } |
Java 8 Program 23:- Given a list of integers, separate odd and even numbers.
package r4r.co.in;
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
public class SeparateOddAndEvenNumbers {
public static void main(String[] args) { //Given a list of integers, separate odd and even numbers Integer[] input= {1,2,3,4,5,6,7,8,9,10}; //Stream.of(input)-stream List<Integer> list=Arrays.asList(input); Map<Boolean, List<Integer>> oddEvenMap=list.stream().collect(Collectors.partitioningBy(s->s%2==0)); System.out.println(oddEvenMap); for (Map.Entry<Boolean,List<Integer>> entry:oddEvenMap.entrySet()) { List<Integer> values=entry.getValue(); Boolean key=entry.getKey(); if(key) System.out.println("Even"); else System.out.println("Odd"); System.out.println(values);
} } } |
Java 8 Program 24 :- How to sort a list of strings by length using Lambda expressions using Java 8.
package r4r.co.in;
import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
public class ShortByLengthOfString {
public static void main(String[] args) {
// How to sort a list of strings by length using Lambda expressions using Java 8 String[] str = { "Rajesh Kumar", "Rajesh", "Kumar", "R4R" ,"Rajesh r4r"}; List<String> list = Stream.of(str).sorted((o1, o2) -> (o1.length() - o2.length())).collect(Collectors.toList()); System.out.print(list); } } |
Java 8 Program 25:- Write a program to sum an array using Java 8
package r4r.co.in;
import java.util.stream.Collectors; import java.util.stream.Stream;
public class SumAnArray { //Write a program to sum an array using Java 8 public static void main(String[] args) { Integer[] input= {1,2,3,4,5,6,7,8,9,10}; int sum=Stream.of(input).collect(Collectors.summingInt(Integer::intValue));
System.err.println(sum); } }
|
Java 8 Program 26:- Write a program to sum an array without using the sum method using Java 8.
package r4r.co.in;
import java.util.stream.Stream;
public class SumWithoutUsingSumMenthod {
public static void main(String[] args) { //Write a program to sum an array without using the sum method using Java 8
Integer[] input= {1,2,34,5,6,7,8,78,9,99,9,5,97,96,79}; Integer sum=Stream.of(input).reduce(0, (x,y)->x+y).intValue(); System.out.print(sum); } } |