0% found this document useful (0 votes)
67 views

Java 8 Coding Interview Answers

Uploaded by

suryachandra4you
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Java 8 Coding Interview Answers

Uploaded by

suryachandra4you
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

Java 8 coding interview questions and solutions.

1. Count total occurrence each char in a string.


pubic static void printEachCharOccurrence(String s){
System.out.println(Arrays.stream(s.toLowerCase().split("")).
collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));
//Or
System.out.println(s.chars().mapToObj(c->(char)c).
collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));
}
2. Count total occurrence each char in a Array list of string.
public static void validateSameChars(List<String> list){

System.out.println(Arrays.stream(list.stream().collect(Collectors.joining()).split(
"")).
collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));
}
3. Sort list of string increasing order by length
public statis void sortStringByLength(String s){
System.out.println(Arrays.stream(s.split(" ")).
sorted(Comparator.comparing(String::length)).collect(Collectors.toList()));
}
4. Reverse each string in a sentence.
public static void reverseEachWord(String s){
String s2= Arrays.stream(s.split(" ")).map(e->new StringBuffer(e).reverse()).
collect(Collectors.joining(" "));
}
5. Remove duplicates from a list.
public static void removeDuplicates(List<String> list){
list.stream().collect(Collectors.toSet());
}
6. Remove duplicates from two lists.
public static void removeDuplicates(List<String> l1, List<String> l2){
Stream.concate(l1.stream(),l2.stream()).collect(Collectors.toSet());
}
7. Verify given Strings are Anagram.
public static void anagramTest(String s1, String s2){
String s3=Arrays.stream(s1.toLowerCase().split("")).sorted().
collect(Collectors.joining());
String s4= Arrays.stream(s2.toLowerCase().split("")).sorted().
collect(Collectors.joining());
if(s3.equals(s4)) {
System.out.println("its Anagram.");
} else{
System.out.println("Given String are not anagram.");
}
}
8. Validate same chars in a given array list of strings.
//Validate same chars in a given array list of strings.
//Or group by same chars in a array list of strings

public static void validateSameChars(List<String> list){


Map<String, Double> map = new HashMap<>();
list.stream().forEach(e->{
double d=Arrays.stream(e.split("")).map(i->(int)i.toCharArray()[0]).
reduce(0,(s1,s2)->s1+s2).doubleValue();
map.put(e,d);
});
Map<Double,List<String>> map2 = map.entrySet().stream().
collect(Collectors.groupingBy(Map.Entry::getValue,Collectors.mapping(Map.Entry::get
Key, Collectors.toList())));
System.out.println(map2);
}
9. Get last element of an ArrayList. Or Get the nth element of an ArrayList.
public static void getNthElement(List<String>list, int n){
if(n==0){
s=list.size()-1;
}
System.out.println(list.stream().skip(n).findFirst().get());
}
10. Find the first non-repeated character in a string.
public static void getNonRepeatedChar(String s){
Map<String, Long> map= Arrays.stream(s.split("")).
collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));
System.out.println(map.entrySet().stream().filter(e->e.getValue()==1).
findFirst().get());
}
11. Find the first repeated character in a string.
public static void getFirstRepectedChars(String s) {
System.out.println(s);
Map<String, Long> map= Arrays.stream(s.split("")).
collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()));
System.out.println(map.entrySet().stream().
filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).
findFirst().get());
}
12 Find Subarray with given sum | Set 1 (Non-negative Numbers)
Given an array arr[] of non-negative integers and an integer sum, find a subarray
that adds to a given sum. There may be more than one subarray with sum as the given
sum, print first such subarray.
/*Examples: Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Explanation: Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33
Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
Explanation: There is no subarray with 0 sum
*/

public static int [] getSubindexArray(int ary[], int sum){


Map<Integer, Integer> intMap= new HashMap<>();
int currentSum=0;
for(int i=0;i<arr.length;i++) {
currentSum+=arr[i];
if(currentSum==sum) {
return new int[] {0,1};
}
if(intMap.containsKey(currentSum-sum)) {
return new int[] {intMap.get(currentSum-sum)+1,i};
}
intMap.put(currentSum,i);
}
return new int[] {};
}
}
Now using Employee Object

import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter@Getter
@ToString
@EqualsAndHashCode
@Builder
public class Employee {
private String empName;
private int empId;
private int age;
private String gender;
private int salary;
private String address1;
private String address2;
private String zipCode;
private String dept;
}
//This code is used for Auto generate 10 Random employees with different data.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ModelHelper {

private static int count=0;


private static List<Employee>arrayList = new ArrayList<Employee>();

public static List<Employee> getEmployeeList(){


if(count==0) {
for(int i=0; i<10; i++) {
int j= randomInt(3);
if(j%2==0)
arrayList.add(getNewMEmp());
else
arrayList.add(getNewFEmp());
}
}
return arrayList;
}
private static Employee getNewMEmp() {
return
Employee.builder().empId(randomInt(5)).empName(random()).salary(randomInt(6)).gende
r("M").age(randomInt(2)).
address1(random()).address2(random()).zipCode(random()).dept(getDeptId()).build();

}
private static Employee getNewFEmp() {
return
Employee.builder().empId(randomInt(5)).empName(random()).salary(randomInt(6)).gende
r("F").age(randomInt(2)).

address1(random()).address2(random()).zipCode(random()).dept(getDeptId()).build();

}
static final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

static final String AB1="abcdefghijklmnopqrstuvwxyz";

private static String random() {


//Generate random name
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
salt.append(AB.charAt(rnd.nextInt(AB.length())));
int length=rnd.nextInt(8);
if(length<3)
length+=3;
while (salt.length() < length) { // length of the random string.
int index = rnd.nextInt(AB1.length());
salt.append(AB1.charAt(index));
}
String saltStr = salt.toString();

return saltStr;
}
private static int randomInt() {
//Generate random number
String SALTCHARS = "123456789";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 4) { // length of the random string.
int index = rnd.nextInt(SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();

return Integer.parseInt(saltStr);
}
private static int randomInt(int s) {//Generate random int
String SALTCHARS = "123456789";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < s) {
int index = rnd.nextInt(SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();

return Integer.parseInt(saltStr);
}
private static String getDeptId() {//Generate Random Deptid
int i= randomInt(9);
if(i%3==0) {
return "A";
} else if(i%3==1) {
return"B";
} else {
return "C";
}
}
}
1. Find all male and female employees.
public static void findAllMaleFemaleEmployees(){
List<Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL);
System.out.println("Find number of M and F employees");
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender(),Collectors.counting())));
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender())));
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender(),Collectors.toList())));
System.out.println("\n\n");
}
2. Find all employees in each department.
public static void findNumberOFEmpsFromEachDept() {
List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL);
System.out.println("number of employees in each department");
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getDept(),Collectors.counting())));
System.out.println("\n\n");
}
3. Find Youngest and Oldest employee.
public static void findYongestEmp() {
List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL);
System.out.println("Find Youngest employee from from org");
System.out.println(empL.stream().min(Comparator.comparingInt(Employee::getAge)));
System.out.println("\n\n");
}

public static void findOldestEmp() {


List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL);
System.out.println("Find senior most employee");
System.out.println(empL.stream().max(Comparator.comparingInt(Employee::getAge)));
System.out.println("\n\n");
}
4. Find the Average age in each department.
public static void findAvgSalarMndF() {
List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender())));
System.out.println("the average salary of male and female employees");
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender(),Collectors.averagingInt(Employee::getSalary))));
System.out.println("\n\n");
}
5. Find the Highest paid employee.
public static void findHightPaid() {
List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println("highest paid employee in the organization ");
System.out.println(empL.stream().max(Comparator.comparingInt(e->e.getSalary())));
System.out.println("\n\n");
}
6. Find Average Salary in Male and Female employees.
public static void findAvgSalarMndF() {
List <Employee> empL = ModelHelper.getEmployeeList();
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender())));
System.out.println("the average salary of male and female employees");
System.out.println(empL.stream().collect(Collectors.groupingBy(e-
>e.getGender(),Collectors.averagingInt(Employee::getSalary))));
System.out.println("\n\n");
}
7. Sort Employees by age and Names.
public static void employeeSortByAgeAndNames() {
List<Employee> empL = ModelHelper.getEmployeeList();
System.out.println("\n\n");
System.out.println(empL);
System.out.println("Sort employees by age and namnes");

System.out.println(empL.stream().sorted(Comparator.comparing(Employee::getAge).then
Comparing(Employee::getEmpName)).collect(Collectors.toList()));
System.out.println("\n\n");
}

You might also like