Sitemap

Java 8 coding Questions

3 min readJun 21, 2024

--

/*Given a list of integers, find the total number of elements present in the
list using Stream functions?*/
import java.util.Arrays;
import java.util.List;

public class CountElements {

public static void main(String[] args) {

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
Long count = myList.stream().count();
System.out.println("Total number of elements is: "+count);

}

}
/*Given a List of Integers find total count, min, max, sum, and the average for numbers by using Stream api
input :list=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29] */

public class CountSumMinMaxAvg {

public static void main(String[] args) {

List<Integer> list = List.of(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);

//total count
Long count = list.stream().count();
System.out.println("Total no. of integers are : "+count);

//find minimum value
list.stream().min(Comparable::compareTo).ifPresent(n->System.out.println("Minimum value is : "+n));

//find maximum value
list.stream().max(Comparable::compareTo).ifPresent(n->System.out.println("Maximum value is : "+n));

//find sum
int sum = list.stream().mapToInt(Integer::intValue).sum();
System.out.println("sum of numbers in list is : "+sum);

//find average
list.stream().mapToInt(Integer::intValue).average().ifPresent(avg->System.out.println("average of number is : "+avg));
}

}

Get Md’s stories in your inbox

Join Medium for free to get updates from this writer.


/*'StringJoiner' is a utility class introduced in Java 8 to simplify the process of constructing
a sequence of characters separated by a delimiter. It can also include a prefix and a suffix around the entire sequence,
which is especially useful for formatting output strings. StringJoiner provides an efficient and flexible way to concatenate
strings without needing to manage delimiters manually.*/
public class StringJoiner {

public static void main(String[] args) {

List<String> countries = List.of("USA", "Japan", "France", "Germany", "Italy", "U.K.", "Canada");

String joinedCountries = countries.stream().collect(Collectors.joining(","));
System.out.println(joinedCountries);

String joinedCountriesWithPrefixSuffix = countries.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println(joinedCountriesWithPrefixSuffix);
}

}
/*Varargs (variable-length argument lists) in Java allow you to pass an 
arbitrary number of arguments to a method. This feature is useful when
you don't know in advance how many arguments will be passed to the method.
Varargs are specified by three dots (...) after the type in the method's
parameter list.*/

public class VarArgs {

public static void main(String[] args) {

printNumbers(1, 2, 3);
printNumbers(10, 20, 30, 40, 50);
printNumbers(); // Empty argument list is also valid

}

public static void printNumbers(int... numbers) {

System.out.println("Number of arguments: "+numbers.length);

for(int number : numbers) {
System.out.print(number+" ");
}

System.out.println();
}
}

// Various Stream API questions on Employee



import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Employee {

private int id;
private String name;
private String department;
private double salary;

Employee(int id, String name, String department,double salary) {
this.id=id;
this.name=name;
this.department=department;
this.salary=salary;
}

public void setId(int id) {
this.id=id;
}

public int getId() {
return id;
}

public void setName(String name) {
this.name=name;
}

public String getName() {
return name;
}

public void setDepartment(String department) {
this.department=department;
}

public String getDepartment() {
return department;
}

public void setSalary(double salary) {
this.salary=salary;
}

public double getSalary() {
return salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department=" + department + ", salary=" + salary + "]";
}


}

public class EmployeeMain {

public static void main(String[] args) {

List<Employee> employee = Arrays.asList(new Employee(1, "sam", "IT", 29090),new Employee(2, "harry", "DEV", 87990),new Employee(3, "jhon", "IT", 34220)
,new Employee(4, "smith", "IT", 343330));

//Find all employees belonging to a specific department (like "IT").
List<Employee> ITEmployee = employee.stream().filter(e->e.getDepartment()=="IT").collect(Collectors.toList());
System.out.println(ITEmployee);

//Get a list of employee names only.
List<String> namedEmployee = employee.stream().map(Employee::getName).collect(Collectors.toList());
System.out.println(namedEmployee);

//Calculate the average salary of all employees.
Double averageSalary = employee.stream().mapToDouble(Employee::getSalary).average().getAsDouble();
System.out.println("average salary of employees is : "+averageSalary);

//find employee with highest and lowest salary
Employee highestSalary = employee.stream().max(Comparator.comparingDouble(Employee::getSalary)).get();
Employee lowestSalary = employee.stream().min(Comparator.comparingDouble(Employee::getSalary)).get();

System.out.println("Highest salary of employee is "+highestSalary);
System.out.println("lowest salary of employee is "+lowestSalary);

//group employees by department
Map<String, List<Employee>> employeesByDepartment = employee.stream().collect(Collectors.groupingBy(Employee::getDepartment));
employeesByDepartment.forEach((dept,empl)->{
System.out.println(dept+" - "+empl);
});

//Get the total salary paid to all employees.
double totalSalary = employee.stream().mapToDouble(Employee::getSalary).sum();
System.out.println("total salary paid to employees : "+totalSalary);

//Get the count of employees in each department.
Map<String, Long> employeeCountByDepartment = employee.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.counting()));
employeeCountByDepartment.forEach((dept,count)->{
System.out.println(dept+" - "+count);
});

//Sort employees by their salary in descending order.
employee.stream().sorted(Comparator.comparingDouble(Employee::getSalary).reversed()).forEach(System.out::println);

//check if any employee earns more than 100000:
boolean hasHighEarner = employee.stream().anyMatch(e -> e.getSalary() > 100000);
System.out.println("Any employee earning more than 100000? " + hasHighEarner);

//collect all employees whose names start with a particular letter (like 's'):
List<Employee> namedEmpl = employee.stream().filter(e->e.getName().startsWith("s")).collect(Collectors.toList());
System.out.println(namedEmpl);

}

}

--

--