0% found this document useful (0 votes)
68 views6 pages

Java 8 Coding Interview Solutions

Uploaded by

suryachandra4you
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views6 pages

Java 8 Coding Interview Solutions

Uploaded by

suryachandra4you
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Java 8 coding interview questions and solutions.

1. Count total occurrence each char in a string.


pubic static void printEachCharOccurrence(String s){
[Link]([Link]([Link]().split("")).
collect([Link]([Link](),[Link]())));
//Or
[Link]([Link]().mapToObj(c->(char)c).
collect([Link]([Link](),[Link]())));
}
2. Count total occurrence each char in a Array list of string.
public static void validateSameChars(List<String> list){

[Link]([Link]([Link]().collect([Link]()).split(
"")).
collect([Link]([Link](),[Link]())));
}
3. Sort list of string increasing order by length
public statis void sortStringByLength(String s){
[Link]([Link]([Link](" ")).
sorted([Link](String::length)).collect([Link]()));
}
4. Reverse each string in a sentence.
public static void reverseEachWord(String s){
String s2= [Link]([Link](" ")).map(e->new StringBuffer(e).reverse()).
collect([Link](" "));
}
5. Remove duplicates from a list.
public static void removeDuplicates(List<String> list){
[Link]().collect([Link]());
}
6. Remove duplicates from two lists.
public static void removeDuplicates(List<String> l1, List<String> l2){
[Link]([Link](),[Link]()).collect([Link]());
}
7. Verify given Strings are Anagram.
public static void anagramTest(String s1, String s2){
String s3=[Link]([Link]().split("")).sorted().
collect([Link]());
String s4= [Link]([Link]().split("")).sorted().
collect([Link]());
if([Link](s4)) {
[Link]("its Anagram.");
} else{
[Link]("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<>();
[Link]().forEach(e->{
double d=[Link]([Link]("")).map(i->(int)[Link]()[0]).
reduce(0,(s1,s2)->s1+s2).doubleValue();
[Link](e,d);
});
Map<Double,List<String>> map2 = [Link]().stream().
collect([Link]([Link]::getValue,[Link]([Link]::get
Key, [Link]())));
[Link](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=[Link]()-1;
}
[Link]([Link]().skip(n).findFirst().get());
}
10. Find the first non-repeated character in a string.
public static void getNonRepeatedChar(String s){
Map<String, Long> map= [Link]([Link]("")).
collect([Link]([Link](),
LinkedHashMap::new, [Link]()));
[Link]([Link]().stream().filter(e->[Link]()==1).
findFirst().get());
}
11. Find the first repeated character in a string.
public static void getFirstRepectedChars(String s) {
[Link](s);
Map<String, Long> map= [Link]([Link]("")).
collect([Link]([Link](),
LinkedHashMap::new, [Link]()));
[Link]([Link]().stream().
filter(entry -> [Link]() > 1).map(entry -> [Link]()).
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<[Link];i++) {
currentSum+=arr[i];
if(currentSum==sum) {
return new int[] {0,1};
}
if([Link](currentSum-sum)) {
return new int[] {[Link](currentSum-sum)+1,i};
}
[Link](currentSum,i);
}
return new int[] {};
}
}
Now using Employee Object

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@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 [Link];
import [Link];
import [Link];

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)
[Link](getNewMEmp());
else
[Link](getNewFEmp());
}
}
return arrayList;
}
private static Employee getNewMEmp() {
return
[Link]().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
[Link]().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();
[Link]([Link]([Link]([Link]())));
int length=[Link](8);
if(length<3)
length+=3;
while ([Link]() < length) { // length of the random string.
int index = [Link]([Link]());
[Link]([Link](index));
}
String saltStr = [Link]();

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

return [Link](saltStr);
}
private static int randomInt(int s) {//Generate random int
String SALTCHARS = "123456789";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while ([Link]() < s) {
int index = [Link]([Link]());
[Link]([Link](index));
}
String saltStr = [Link]();

return [Link](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 = [Link]();
[Link](empL);
[Link]("Find number of M and F employees");
[Link]([Link]().collect([Link](e-
>[Link](),[Link]())));
[Link]([Link]().collect([Link](e-
>[Link]())));
[Link]([Link]().collect([Link](e-
>[Link](),[Link]())));
[Link]("\n\n");
}
2. Find all employees in each department.
public static void findNumberOFEmpsFromEachDept() {
List <Employee> empL = [Link]();
[Link](empL);
[Link]("number of employees in each department");
[Link]([Link]().collect([Link](e-
>[Link](),[Link]())));
[Link]("\n\n");
}
3. Find Youngest and Oldest employee.
public static void findYongestEmp() {
List <Employee> empL = [Link]();
[Link](empL);
[Link]("Find Youngest employee from from org");
[Link]([Link]().min([Link](Employee::getAge)));
[Link]("\n\n");
}

public static void findOldestEmp() {


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

[Link]([Link]().sorted([Link](Employee::getAge).then
Comparing(Employee::getEmpName)).collect([Link]()));
[Link]("\n\n");
}

Common questions

Powered by AI

To calculate the average salary for male and female employees, use `Collectors.groupingBy()` to group employees by gender, along with `Collectors.averagingInt()` to compute the averages: `empL.stream().collect(Collectors.groupingBy(e -> e.getGender(), Collectors.averagingInt(Employee::getSalary)))` .

Random Employee objects can be generated by using a helper class `ModelHelper` that utilizes `Random` to create employee attributes like id, name, and gender. Once generated, use `Collectors.groupingBy()` to categorize employees by gender: `empL.stream().collect(Collectors.groupingBy(e -> e.getGender(), Collectors.toList()))` .

To remove duplicates from two lists and output the unique elements, concatenate the streams of both lists using `Stream.concat()`, then collect them into a `Set` using `Collectors.toSet()` which inherently removes duplicates: `Stream.concat(l1.stream(), l2.stream()).collect(Collectors.toSet())` .

To find the youngest employee, utilize the `min()` method on the employee stream, using a comparator that compares ages: `empL.stream().min(Comparator.comparingInt(Employee::getAge))` .

To count the total occurrences of each character in an array list of strings, use Java 8 streams by first concatenating the strings in the list, then splitting the resulting string into individual characters. Utilize `Collectors.groupingBy()` alongside `Collectors.counting()` to group and count each character: `Arrays.stream(list.stream().collect(Collectors.joining()).split("")) .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))` .

To validate if two strings are anagrams, convert both strings to lowercase, split them into character arrays, sort them, and then join them back. If the resulting strings are equal, then the original strings are anagrams: `String s3=Arrays.stream(s1.toLowerCase().split("")).sorted().collect(Collectors.joining()); String s4= Arrays.stream(s2.toLowerCase().split("")).sorted().collect(Collectors.joining()); return s3.equals(s4);` .

To find the first non-repeated character in a string using Java 8, split the string into characters and collect them into a `LinkedHashMap` with character counts. Then, filter the entry set to find the first entry with a count of one: `Map<String, Long> map = Arrays.stream(s.split("")) .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())); return map.entrySet().stream().filter(e -> e.getValue() == 1).findFirst().get()` .

To reverse each word in a sentence, first split the sentence into words using `split(" ")`, then apply `StringBuffer(e).reverse()` on each word, and finally join the reversed words with spaces using `Collectors.joining(" ")`. The method `reverseEachWord(String s)` demonstrates this: `String s2 = Arrays.stream(s.split(" ")).map(e->new StringBuffer(e).reverse()).collect(Collectors.joining(" "));` .

To find the highest paid employee in a list of Employee objects, use the `max()` method with a comparator that compares by salary: `empL.stream().max(Comparator.comparingInt(Employee::getSalary))` .

To find the first subarray with a given sum, maintain a cumulative sum and use a hashmap to store each sum with its index. As you iterate through the array, check if `currentSum - sum` exists in the hashmap, indicating a subarray with the desired sum between indices: `for (int i = 0; i < arr.length; i++) { currentSum += arr[i]; if (currentSum == sum) return new int[] {0, i}; if (intMap.containsKey(currentSum - sum)) return new int[] {intMap.get(currentSum - sum) + 1, i}; intMap.put(currentSum, i); }` .

You might also like