diff --git a/EvenAndOddPrinter.java b/EvenAndOddPrinter.java new file mode 100644 index 0000000..6f10674 --- /dev/null +++ b/EvenAndOddPrinter.java @@ -0,0 +1,39 @@ +package com.javatechie; + +import java.util.concurrent.CompletableFuture; +import java.util.function.IntPredicate; +import java.util.stream.IntStream; + +public class EvenAndOddPrinter { + + private static Object object = new Object(); + + private static IntPredicate evenCondition = e -> e % 2 == 0; + private static IntPredicate oddCondition = e -> e % 2 != 0; + + + public static void main(String[] args) throws InterruptedException { + CompletableFuture.runAsync(() -> EvenAndOddPrinter.printResults(oddCondition)); + CompletableFuture.runAsync(() -> EvenAndOddPrinter.printResults(evenCondition)); + Thread.sleep(1000); + } + + public static void printResults(IntPredicate condition) { + IntStream.rangeClosed(1, 10) + .filter(condition) + .forEach(EvenAndOddPrinter::execute); + } + + + public static void execute(int i) { + synchronized (object) { + try { + System.out.println("Thread Name " + Thread.currentThread().getName() + " : " + i); + object.notify(); + object.wait(); + } catch (InterruptedException ex) { + //error log + } + } + } +} diff --git a/EvenAndOddPrinterBy2Threads.java b/EvenAndOddPrinterBy2Threads.java new file mode 100644 index 0000000..b7ed6bd --- /dev/null +++ b/EvenAndOddPrinterBy2Threads.java @@ -0,0 +1,46 @@ +package com.javatechie; + +public class EvenAndOddPrinterBy2Threads implements Runnable { + + static int count = 1; + Object object; + + public EvenAndOddPrinterBy2Threads(Object object) { + this.object = object; + } + + @Override + public void run() { + + while (count <= 100) { + if (count % 2 == 0 && Thread.currentThread().getName().equals("even")) { + synchronized (object) { + System.out.println("Thread Name : " + Thread.currentThread().getName() + " value :" + count); + count++; + try { + object.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + if (count % 2 != 0 && Thread.currentThread().getName().equals("odd")) { + synchronized (object) { + System.out.println("Thread Name : " + Thread.currentThread().getName() + " value :" + count); + count++; + object.notify(); + } + } + + } + + } + + public static void main(String[] args) { + Object lock=new Object(); + Runnable r1=new EvenAndOddPrinterBy2Threads(lock); + Runnable r2=new EvenAndOddPrinterBy2Threads(lock); + new Thread(r1, "even").start(); + new Thread(r2, "odd").start(); + } +} diff --git a/EvenAndOddPrinterByES.java b/EvenAndOddPrinterByES.java new file mode 100644 index 0000000..54d351f --- /dev/null +++ b/EvenAndOddPrinterByES.java @@ -0,0 +1,36 @@ +package com.javatechie; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.IntStream; + +public class EvenAndOddPrinterByES { + + public static void main(String[] args) { + + ExecutorService executorService = Executors.newFixedThreadPool(2); + + IntStream.rangeClosed(1, 10) + .forEach(num -> { + CompletableFuture oddCompletableFuture = CompletableFuture.completedFuture(num) + .thenApplyAsync(x -> { + if (x % 2 != 0) { + System.out.println("Thread Name " + Thread.currentThread().getName() + " : " + x); + } + return num; + }, executorService); + oddCompletableFuture.join(); + + CompletableFuture evenCompletableFuture = CompletableFuture.completedFuture(num) + .thenApplyAsync(x -> { + if (x % 2 == 0) { + System.out.println("Thread Name " + Thread.currentThread().getName() + " : " + x); + } + return num; + }, executorService); + evenCompletableFuture.join(); + }); + executorService.shutdown(); + } +} diff --git a/NthHighestSalaryDemo.java b/NthHighestSalaryDemo.java new file mode 100644 index 0000000..63e7c26 --- /dev/null +++ b/NthHighestSalaryDemo.java @@ -0,0 +1,60 @@ +package com.javatechie; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class NthHighestSalaryDemo { + + public static void main(String[] args) { + + Map map1 = new HashMap<>(); + map1.put("anil", 1000); + map1.put("bhavna", 1300); + map1.put("micael", 1500); + map1.put("tom", 1600);//output + map1.put("ankit", 1200); + map1.put("daniel", 1700); + map1.put("james", 1400); + + Map.Entry results = getNthHighestSalary(4, map1); + System.out.println(results); + + Map map2 = new HashMap<>(); + map2.put("anil", 1000); + map2.put("ankit", 1200); + map2.put("bhavna", 1200); + map2.put("james", 1200); + map2.put("micael", 1000); + map2.put("tom", 1300); + map2.put("daniel", 1300); + + //System.out.println(getNthHighestSalary(2, map2)); + + + System.out.println(getDynamicNthHighestSalary(3, map1)); + + } + + public static Map.Entry getNthHighestSalary(int num, Map map) { + return map.entrySet().stream() + .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) + .collect(Collectors.toList()) + .get(num - 1); + } + + public static Map.Entry> getDynamicNthHighestSalary(int num, Map map) { + return map.entrySet() + .stream() + .collect(Collectors.groupingBy(Map.Entry::getValue, + Collectors.mapping(Map.Entry::getKey, Collectors.toList()) + )) + .entrySet() + .stream() + .sorted(Collections.reverseOrder(Map.Entry.comparingByKey())) + .collect(Collectors.toList()) + .get(num - 1); + } +} diff --git a/java8/Employee.java b/java8/Employee.java new file mode 100644 index 0000000..ebf0723 --- /dev/null +++ b/java8/Employee.java @@ -0,0 +1,24 @@ +package com.java8; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +class Employee{ + + private int id; + private String name; + private String dept; + private List projects; + private double salary; + private String gender; + +} + diff --git a/java8/EmployeeDataBase.java b/java8/EmployeeDataBase.java new file mode 100644 index 0000000..a934918 --- /dev/null +++ b/java8/EmployeeDataBase.java @@ -0,0 +1,35 @@ +package com.java8; + +import java.util.Arrays; +import java.util.List; + +public class EmployeeDataBase { + + public static List getAllEmployees() { + Project p1 = new Project("P001", "Alpha", "ABC Corp", "Alice"); + Project p2 = new Project("P002", "Beta", "XYZ Ltd", "Bob"); + Project p3 = new Project("P003", "Gamma", "ABC Corp", "Alice"); + Project p4 = new Project("P004", "Delta", "TechWorld", "Charlie"); + Project p5 = new Project("P005", "Epsilon", "MoneyMatters", "Daniel"); + Project p6 = new Project("P006", "Zeta", "SmartTech", "Eva"); + Project p7 = new Project("P007", "Eta", "BrandBoost", "George"); + Project p8 = new Project("P008", "Theta", "InnoSoft", "Hannah"); + Project p9 = new Project("P009", "Iota", "FastTrack", "Ian"); + Project p10 = new Project("P010", "Kappa", "DigitalWave", "Jessica"); + + // Employee instances + Employee e1 = new Employee(1, "John Doe", "Development", Arrays.asList(p1, p2), 80000, "Male"); + Employee e2 = new Employee(2, "Jane Smith", "Development", Arrays.asList(p3), 80000, "Female"); + Employee e3 = new Employee(3, "Robert Brown", "Sales", Arrays.asList(p4), 60000, "Male"); + Employee e4 = new Employee(4, "Lisa White", "HR", Arrays.asList(p1), 55000, "Female"); + Employee e5 = new Employee(5, "Michael Green", "Finance", Arrays.asList(p5), 90000, "Male"); + Employee e6 = new Employee(6, "Sophia Brown", "Development", Arrays.asList(p6), 85000, "Female"); + Employee e7 = new Employee(7, "James Wilson", "Marketing", Arrays.asList(p7), 72000, "Male"); + Employee e8 = new Employee(8, "Olivia Harris", "Development", Arrays.asList(p8), 88000, "Female"); + Employee e9 = new Employee(9, "William Lee", "Sales", Arrays.asList(p9), 78000, "Male"); + Employee e10 = new Employee(10, "Emily Clark", "Development", Arrays.asList(p10), 95000, "Female"); + + // Print employee details (just for testing) + return Arrays.asList(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); + } +} diff --git a/java8/Java8MethodCheatSheet.java b/java8/Java8MethodCheatSheet.java new file mode 100644 index 0000000..c0267d7 --- /dev/null +++ b/java8/Java8MethodCheatSheet.java @@ -0,0 +1,176 @@ +package com.java8; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Java8MethodCheatSheet { + + public static void main(String[] args) { + + + List employees = EmployeeDataBase.getAllEmployees(); + + // forEach + //employees.forEach(e-> System.out.println(e.getName()+" : "+e.getSalary())); + + //employees.stream().forEach(System.out::println); + + //filter + //.collect + + Map developmentEmployees = employees.stream() + .filter(e -> e.getDept().equals("Development") && e.getSalary() > 80000) + .collect(Collectors.toMap(Employee::getId, Employee::getName)); + + // System.out.println(developmentEmployees); + + //map + //distinct + List depts = employees.stream() + .map(Employee::getDept) + .distinct() + .collect(Collectors.toList()); + //System.out.println(depts); + + List> projectNames = employees.stream() + .map(e -> e.getProjects() + .stream().map(p -> p.getName())).collect(Collectors.toList()); + + //flatMap + + List projects = employees.stream() + .flatMap(e -> e.getProjects().stream()) + .map(p -> p.getName()).distinct() + .collect(Collectors.toList()); + + //System.out.println(projects); + + + //sorted + //asc + List ascSortedEmployees = employees.stream() + .sorted(Comparator.comparing(Employee::getSalary)) + .collect(Collectors.toList()); + +// ascSortedEmployees.get(0); + + //ascSortedEmployees.forEach(System.out::println); + + //desc + List descSortedEmployees = employees.stream() + .sorted(Collections.reverseOrder(Comparator.comparing(Employee::getSalary))) + .collect(Collectors.toList()); + +// descSortedEmployees.get(0); + + //descSortedEmployees.forEach(System.out::println); + + //min & max + Optional highestPaidEmployees = employees.stream() + .max(Comparator.comparingDouble(Employee::getSalary)); + + // System.out.println("Highest paid employee : "+highestPaidEmployees); + + Optional lowestPaidEmployees = employees.stream() + .min(Comparator.comparingDouble(Employee::getSalary)); + + //System.out.println("Lowest paid employee : "+lowestPaidEmployees); + + //groupingBy + + Map> employeeGroup = employees.stream() + .collect(Collectors.groupingBy(Employee::getGender)); + + //System.out.println(employeeGroup); + + //Gender -> [names] + Map> employeeGroupNames = employees.stream() + .collect(Collectors.groupingBy(Employee::getGender, + Collectors.mapping(Employee::getName, Collectors.toList()) + )); + + //System.out.println(employeeGroupNames); + + //Gender -> [count] + Map employeeGroupCountMap = employees.stream() + .collect(Collectors.groupingBy(Employee::getGender, Collectors.counting())); + System.out.println(employeeGroupCountMap); + + //findFirst + + Employee findFirstElement = employees.stream() + .filter(e -> e.getDept().equals("Development")) + .findFirst() + .orElseThrow(()->new IllegalArgumentException("Employee not found ")); + +// System.out.println(findFirstElement.get());//NPE +// +// if(findFirstElement.isPresent()){ +// System.out.println(findFirstElement.get()); +// } +// +// findFirstElement.ifPresent(e-> System.out.println(e.getName())); + + //System.out.println(findFirstElement); + + //findAny + + Employee findAnyElement = employees.stream() + .filter(e -> e.getDept().equals("Development")) + .findAny() + .orElseThrow(()->new IllegalArgumentException("Employee not found ")); + + // System.out.println(findAnyElement); + + //anyMatch(Predicate) , allMatch(Predicate) , noneMatch(Predicate) + + boolean developmentEmpAnyMatch = employees.stream() + .anyMatch(e -> e.getDept().equals("Development")); + //System.out.println("is there any employee match from development dept "+developmentEmpAnyMatch); + + + boolean developmentEmpAllMatch = employees.stream() + .allMatch(e -> e.getSalary()>50000);//55000 + //System.out.println(developmentEmpAllMatch); //false + + + boolean isNoneMatch = employees.stream() + .noneMatch(e -> e.getDept().equals("abc")); + //System.out.println(isNoneMatch); + + //limit(long) + + List topPaidEmployees = employees.stream() + .sorted(Comparator.comparing(Employee::getSalary).reversed()) + .limit(4) + .collect(Collectors.toList()); + + topPaidEmployees.forEach(e-> System.out.println(e.getName())); + + //skip(long) + List skipEmployees = employees.stream().skip(10) + .collect(Collectors.toList()); + + +// +// forEach(Consumer) +// filter(Predicate) +// collect(Collector) +// map(Function) +// distinct() +// flatMap(Function) +// sorted(Comparator both ASC and DESC) +// min() & max() +// GroupBy +// findFirst() +// findAny() +// anyMatch(Predicate) +// allMatch(Predicate) +// noneMatch(Predicate) +// limit(long maxSize) +// skip(long n) + + + } +} diff --git a/java8/Project.java b/java8/Project.java new file mode 100644 index 0000000..651d42c --- /dev/null +++ b/java8/Project.java @@ -0,0 +1,18 @@ +package com.java8; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +class Project{ + + private String projectCode; + private String name ; + private String client; + private String buLeadName; +} \ No newline at end of file diff --git a/qa/Java8CommonProgrammingQA.java b/qa/Java8CommonProgrammingQA.java new file mode 100644 index 0000000..72b51f7 --- /dev/null +++ b/qa/Java8CommonProgrammingQA.java @@ -0,0 +1,100 @@ +package com.interview.qa; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Java8CommonProgrammingQA { + + public static void main(String[] args) { + List studentList = Stream.of( + new Student(1, "Rohit", 30, "Male", "Mechanical Engineering", "Mumbai", 122, Arrays.asList("+912632632782", "+1673434729929")), + new Student(2, "Pulkit", 56, "Male", "Computer Engineering", "Delhi", 67, Arrays.asList("+912632632762", "+1673434723929")), + new Student(3, "Ankit", 25, "Female", "Mechanical Engineering", "Kerala", 164, Arrays.asList("+912632633882", "+1673434709929")), + new Student(4, "Satish Ray", 30, "Male", "Mechanical Engineering", "Kerala", 26, Arrays.asList("+9126325832782", "+1671434729929")), + new Student(5, "Roshan", 23, "Male", "Biotech Engineering", "Mumbai", 12, Arrays.asList("+012632632782")), + new Student(6, "Chetan", 24, "Male", "Mechanical Engineering", "Karnataka", 90, Arrays.asList("+9126254632782", "+16736784729929")), + new Student(7, "Arun", 26, "Male", "Electronics Engineering", "Karnataka", 324, Arrays.asList("+912632632782", "+1671234729929")), + new Student(8, "Nam", 31, "Male", "Computer Engineering", "Karnataka", 433, Arrays.asList("+9126326355782", "+1673434729929")), + new Student(9, "Sonu", 27, "Female", "Computer Engineering", "Karnataka", 7, Arrays.asList("+9126398932782", "+16563434729929", "+5673434729929")), + new Student(10, "Shubham", 26, "Male", "Instrumentation Engineering", "Mumbai", 98, Arrays.asList("+912632646482", "+16734323229929"))) + .collect(Collectors.toList()); + + // 1. Find the list of students whose rank is in between 50 and 100 + + List students = studentList.stream().filter(student -> student.getRank() > 50 && student.getRank() < 100) + .collect(Collectors.toList()); + // System.out.println(students); + + //2. Find the Students who stays in Karnataka and sort them by their names + + List studentsByCity = studentList.stream().filter(student -> student.getCity().equals("Karnataka")) + .sorted(Comparator.comparing(Student::getFirstName,Comparator.reverseOrder())).collect(Collectors.toList()); + // System.out.println(studentsByCity); + + // 3. Find all departments names + + List deptNames = studentList.stream() + .map(Student::getDept) + .distinct() + .collect(Collectors.toList()); + + Set deptNamesInSet = studentList + .stream().map(Student::getDept) + .collect(Collectors.toSet()); + + //System.out.println(deptNames); + //System.out.println(deptNamesInSet); + + //4. Find all the contact numbers + List contacts = studentList.stream() + .flatMap(student -> student.getContacts().stream()) + .distinct() + .collect(Collectors.toList()); + System.out.println(contacts); + //one2one-> map + //one2many-> flatmap + + //5. Group The Student By Department Names + + + Map> studentMap = studentList.stream() + .collect(Collectors.groupingBy(Student::getDept)); + // System.out.println(studentMap); + + + //6. Find the department who is having maximum number of students + Map.Entry results = studentList.stream() + .collect(Collectors.groupingBy(Student::getDept, Collectors.counting())) + .entrySet().stream().max(Map.Entry.comparingByValue()).get(); + + System.out.println(results); + + //7. Find the average age of male and female students + + Map avgStudents = studentList.stream() + .collect(Collectors + .groupingBy(Student::getGender, + Collectors.averagingInt(Student::getAge))); + + //System.out.println(avgStudents); + + //8. Find the highest rank in each department + + Map> stdMap = studentList.stream() + .collect(Collectors.groupingBy(Student::getDept, + Collectors.minBy(Comparator.comparing(Student::getRank)))); + // System.out.println(stdMap); + + //9 .Find the student who has second rank + + Student student = studentList.stream() + .sorted(Comparator.comparing(Student::getRank)) + .skip(2) + .findFirst().get(); + System.out.println(student); + + } + + +} diff --git a/qa/Student.java b/qa/Student.java new file mode 100644 index 0000000..e79dd7f --- /dev/null +++ b/qa/Student.java @@ -0,0 +1,118 @@ +package com.interview.qa; + +import java.util.List; +import java.util.Objects; + +public class Student { + + private int id; + private String firstName; + private int age; + private String gender; + private String dept; + private String city; + private int rank; + private List contacts; + + public Student(int id, String firstName, int age, String gender, String dept, String city, int rank, List contacts) { + this.id = id; + this.firstName = firstName; + this.age = age; + this.gender = gender; + this.dept = dept; + this.city = city; + this.rank = rank; + this.contacts = contacts; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getDept() { + return dept; + } + + public void setDept(String dept) { + this.dept = dept; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getRank() { + return rank; + } + + public void setRank(int rank) { + this.rank = rank; + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Student student = (Student) o; + return id == student.id && age == student.age && rank == student.rank && Objects.equals(firstName, student.firstName) && Objects.equals(gender, student.gender) && Objects.equals(dept, student.dept) && Objects.equals(city, student.city) && Objects.equals(contacts, student.contacts); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstName, age, gender, dept, city, rank, contacts); + } + + @Override + public String toString() { + return "Student{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", age=" + age + + ", gender='" + gender + '\'' + + ", dept='" + dept + '\'' + + ", city='" + city + '\'' + + ", rank=" + rank + + ", contacts=" + contacts + + '}'; + } +} \ No newline at end of file