Skip to main content

 Java 8 Streams Interview Questions


1. Given a list of integers, write a Java 8 Stream program to find the sum of all even numbers in the list.

List<Integer> numbers =Arrays.asList(1,2,7, 8,9,6,3);
int sum = numbers.stream().filter(n-> n%2==0).mapToInt(Integer::intValue).sum();
System.out.println(sum);
Output : 16
2.Given a list of numbers, write a Java 8 Stream program to find the second largest number in the list.
List<Integer> numbers =Arrays.asList(1,2,7, 8,9,6,3);
int secondLargestNumber = numbers.stream().sorted(Collections.reverseOrder()).skip(1).findFirst().orElse(-1);
System.out.println("second largest number is :" + secondLargestNumber);
output : 
second largest number is :8
3.Given a list of integers, write a Java 8 Stream program to find the average of all the numbers in the list.
List<Integer> numbers =Arrays.asList(1,2,7, 8,9,6,3);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("avergae is " + average);
output: 
avergae is 5.142857142857143
4.Given a list of integers, write a Java 8 Stream program to find the product of all numbers in the list.
List<Integer> numbers =Arrays.asList(1,2,7, 8,9,6,3);
long product = numbers.stream().reduce(1, (n ,m)-> n*m);
System.out.println("the product of all number is :" + product);
output: 
the product of all number is :18144
5.Given a list of strings, write a Java 8 Stream program to count the number of strings that contain the letter 'a' in the list.
List<String> str = Arrays.asList("John", "Vincent", "Erwan");
long count = str.stream().filter(s -> s.contains("a")).count();
System.out.println(count);
output:1
6. Given a list of strings, write a Java 8 Stream program to find the shortest string in the list.
List<String> str = Arrays.asList("John", "Vincent", "Erwan");
String shortestString = str.stream().min(Comparator.comparing(String::length)).get();
System.out.println("shortest String is:" + shortestString);
output: shortest String is:John
7.Given a list of strings, write a Java 8 Stream program to find the longest string in the list.
List<String> str = Arrays.asList("John", "Vincent", "Erwan");
String longestStr = str.stream().max(Comparator.comparing(String::length)).get();
System.out.println("longest String is:" + longestStr);
ouput: longest String is:Vincent
8. Given a list of strings, write a Java 8 Stream program to find the number of strings that have more than 5 characters.
List<String> str = Arrays.asList("John", "Vincent", "Erwan");
long strGreaterThanFive = str.stream().filter( n -> n.length()>5).count();
System.out.println("string count greater than five :" + strGreaterThanFive);
output: string count greater than five :1
9.Given a list of Person objects (
each Person object has a name and age), write a Java 8 Stream program to find the oldest person in the list.
public class Person {

private String name;
private int age;


public Person(String name , int age){
this.name = name;
this.age = age;
}

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;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

List<Person> persons = Arrays.asList(new Person("Emilie", 30), new Person("Benoit", 32), new Person("Alexandre", 23));
Person person = persons.stream().max(Comparator.comparingInt(Person::getAge)).get();

System.out.println(person);
output : Person{name='Benoit', age=32}

10. Given a list of Employee objects (each Employee object has a name, age, and salary), 
write a Java 8 Stream program to find the total salary of all employees over the age of 30
public class Employee {

private String empId;
private String firstName;
private String lastName;
private String email;
private String gender;
private String newJoiner;
private int salary;
private int rating;
private int age;


//getter setter and constructor
}
List<Employee> employees = Arrays.asList(
new Employee("59-385-1088","Zacharias","Schwerin","zchwerin@gmail.com","Male","True",101146,0, 32),
new Employee("73-274-6476","Kyle","Frudd","kfrudd1@ovh.net","Male","FALSE",29310,2, 30),
new Employee("85-939-9584","Axe","Gumb","agumb2@twitter.com","Female","FALSE",62291,4, 25),
new Employee("08-180-8292","Robinet","Batterham","rbatterham3@last.fm","Male","FALSE",142439,4, 28),
new Employee("21-825-2623","Ulick","Burrel","uburrel4@google.ru","Male","FALSE",128764,5, 40),
new Employee("66-708-5539","Tailor","Ridding","Ridding","Female","FALSE",152924,4, 22),
new Employee("81-697-2363","Joete","Braybrooke","jbraybrooke6@prnewswire.com","Male","TRUE",128907,0, 45),
new Employee("63-019-1110","Elroy","Baverstock","ebaverstock7@ehow.com","Male","TRUE",2510,0, 21)
);
long totalSalary = employees.stream().filter(e -> e.getAge()>30).mapToInt(Employee::getSalary).sum();
System.out.println("total salary of emplyee whose age > 30 : " + totalSalary);
output :total salary of emplyee whose age > 30 : 358817

Comments

Popular posts from this blog

How to create Annotation in Spring boot

 To create Custom Annotation in JAVA, @interface keyword is used. The annotation contains :  1. Retention :  @Retention ( RetentionPolicy . RUNTIME ) It specifies that annotation should be available at runtime. 2. Target :  @Target ({ ElementType . METHOD }) It specifies that the annotation can only be applied to method. The target cane be modified to:   @Target ({ ElementType . TYPE }) for class level annotation @Target ({ ElementType . FIELD }) for field level annotation @Retention ( RetentionPolicy . RUNTIME ) @Target ({ ElementType . FIELD }) public @ interface CustomAnnotation { String value () default "default value" ; } value attribute is defined with @ CustomAnnotation annotation. If you want to use the attribute in annotation. A single attribute value. Example : public class Books {           @CustomAnnotation(value = "myBook")     public void updateBookDetail() {         ...

Kafka And Zookeeper SetUp

 Kafka And Zookeeper SetUp zookeeper download Link : https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.8.3/apache-zookeeper-3.8.3-bin.tar.gz Configuration: zoo.conf # The number of milliseconds of each tick tickTime =2000 # The number of ticks that the initial # synchronization phase can take initLimit =10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit =5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir =/tmp/zookeeper # the port at which the clients will connect clientPort =2181 4 char whitelist in command arguments 4lw.commands.whitelist =* Start ZooKeeper Server $ bin/zkServer.sh start Check zookeeper status dheeraj.kumar@Dheeraj-Kumar bin % echo stat | nc localhost 2181 stat is 4 character whitelisted argument  Check Kafka running status : echo dump | nc localhost 2181 | grep broker Responsibility of Leader in Zookeeper: 1. Distrib...

Cache Policy

Cache policies determine how data is stored and retrieved from a cache, which is a small and fast storage area that holds frequently accessed data to reduce the latency of accessing that data from a slower, larger, and more distant storage location, such as main memory or disk. Different cache policies are designed to optimize various aspects of cache performance, including hit rate, latency, and consistency. Here are some common types of cache policies: Least Recently Used (LRU): LRU is a commonly used cache replacement policy. It evicts the least recently accessed item when the cache is full. LRU keeps track of the order in which items were accessed and removes the item that has not been accessed for the longest time. First-In-First-Out (FIFO): FIFO is a simple cache replacement policy. It removes the oldest item from the cache when new data needs to be stored, regardless of how frequently the items have been accessed. Most Recently Used (MRU): MRU removes the most recently accessed ...