Java 8 Innards Hands-on Solution | TCS Fresco Play
Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.
Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).
Solutions:- The Course Id of Java 8 Innards is 55961. It is completely related to new features of java languages. You will learn Stream API, Lambda Expression, Functional Interface, Annotations, etc.
1. Lambda Expression
import java.io.*;
import java.util.*;
class Employee
{
// WRITE CODE OF CONSTRUCTOR
String name;
int id;
int age;
public Employee(String name,int id,int age){
this.name = name;
this.id = id;
this.age = age;
}
}
class SortEmployees
{
void sortEmployees(ArrayList<Employee> empList)
{
// LAMBDA EXPRESSION CODE
Collections.sort(empList,(o1,o2) -> o1.name.compareTo(o2.name));
for(Employee x:empList)
{
System.out.println(x.name+" "+x.id+" "+x.age);
}
}
}
public class SortEmployeesMain
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<Employee> empList=new ArrayList<>();
int n=Integer.parseInt(br.readLine().trim());
for(int i=0;i<n;i++)
{
String inp=br.readLine();
String inparr[]=inp.split(" ");
Employee ws=new Employee(inparr[0],Integer.parseInt(inparr[1]), Integer.parseInt(inparr[2]));
empList.add(ws);
}
SortEmployees s1=new SortEmployees();
s1.sortEmployees(empList);
}
}
2. Java Interface Hands-On (1):-
import java.io.*;
import java.util.function.Consumer;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.function.*;
import java.math.BigInteger;
class PrimeComposite_Factorial
{
void primeOrComposite(int n)
{
//Enter your Code here
if(n<=1)
System.out.println("Neither Prime Nor Composite");
else{
Predicate<Integer> lesser = (x) -> {
boolean res = IntStream.rangeClosed(2,x/2).noneMatch(i-> x%i==0);
return res;
};
if(lesser.test(n))
{
Consumer<Integer> lesserthan = (x) -> {
System.out.println("Prime");
};
lesserthan.accept(n);
}
else{
System.out.println("Composite");
}
}
}
void findFactorial(int n)
{
//Enter your Code here
Consumer<Integer> con = (a) -> {
BigInteger n1 = BigInteger.valueOf(n);
BigInteger sum = BigInteger.ONE;
for(BigInteger i = BigInteger.ONE;i.compareTo(n1) <= 0;i=i.add(BigInteger.ONE)) {
sum = sum.multiply(i);
}
System.out.println(sum);
};
con.accept(n);
}
}
public class PrimeComposite_FactorialMain
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine().trim());
PrimeComposite_Factorial xyz=new PrimeComposite_Factorial();
xyz.primeOrComposite(n);
xyz.findFactorial(n);
}
}
3. Java Interfaces Hands-on(2) Solution:-
import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.function.Consumer;
import java.util.function.Supplier;
class StoreElementsInCollection
{
static void storeElements(String input)
{
//Enter your Code here
List<String> res = new ArrayList<String>();
Consumer<String> rest = (str) ->
{
String rest1[] = str.split(",");
for(int i=0;i<rest1.length;i++)
{
// All should be in lowercase in equal.
if(rest1[i].equals("cheese sandwich") || rest1[i].equals("corn sandwich")|| rest1[i].equals("mix veg sandwich")){
res.add(i,rest1[i]);
}
else
{
System.out.println("Incorrect Input");
return;
}
}
res.forEach((x) -> System.out.println(x));
};
Supplier<List<String>> MNCAnswers = ()-> res;
rest.accept(input);
}
}
public class StoreElementsInCollectionMain
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String input=br.readLine();
StoreElementsInCollection.storeElements(input);
}
}
4. Method Reference
import java.io.*;
import java.util.*;
interface AnonymousInterface
{
void getCipher(ArrayList<String> list);
}
class Cipher_Anonymous
{
void anonymousClass(ArrayList<String> list)
{
//Enter your Code here
AnonymousInterface obj = new AnonymousInterface(){
@Override
public void getCipher(ArrayList<String> list) {
// TODO Auto-generated method stub
for(String x:list){
System.out.print(x);
}
}
};
obj.getCipher(list);
}
}
class Cipher_MethodRef
{
void methodReference(ArrayList<String> list)
{
//Enter your Code here
AnonymousInterface obj = (list1) ->{
list1.forEach(System.out::print);
};
obj.getCipher(list);
}
}
class Cipher_LambdaExp
{
void lambdaExpression(ArrayList<String> list)
{
//Enter your Code here
AnonymousInterface obj = (list1) -> {
for(int i=0;i<list1.size();i++){
int ch = (int)list1.get(i).charAt(0);
String req = list1.get(i).substring(1);
list1.set(i,ch+req);
if(list1.get(i).equals("32"))
list1.set(i,"#$");
StringBuilder sb = new StringBuilder(list1.get(i));
list1.set(i,sb.reverse().toString());
}
for(String x:list1){
System.out.print(x);
}
};
obj.getCipher(list);
}
}
public class CipherMain{
// Already Code Available Here
}
5. Stream API
import java.io.*;
import java.util.*;
class Candidates
{
//Create the Constructor here
//Check Sample Case for more understanding
String name;
String locality;
int age;
public Candidates(String name,String locality,int age){
this.name = name;
this.locality = locality;
this.age = age;
}
}
class Interview_Candidates
{
boolean areNatives(ArrayList<Candidates> candidatesList)
{
//Enter your Code here
int res = (int)candidatesList.stream().filter((c) ->
c.locality.equals("Native")).count();
return res == candidatesList.size();
}
Candidates youngestCandidate(ArrayList<Candidates> candidatesList)
{
//Enter your Code here
Collections.sort(candidatesList,(o1,o2) -> o1.age - o2.age);
return candidatesList.get(0);
}
}
public class Interview_CandidatesMain
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<Candidates> candidatesList=new ArrayList<>();
int n=Integer.parseInt(br.readLine().trim());
for(int i=0;i<n;i++)
{
String inp=br.readLine();
String inparr[]=inp.split("-");
Candidates cnd=new Candidates( inparr[0], inparr[1], Integer.parseInt(inparr[2]) );
candidatesList.add(cnd);
}
Interview_Candidates ic=new Interview_Candidates();
boolean ans= ic.areNatives(candidatesList);
if(ans)
System.out.println("All candidates are Natives");
else
System.out.println("All candidates are not Natives");
Candidates youngest=ic.youngestCandidate(candidatesList);
System.out.println("Details of the Candidate with youngest age : Name = "+youngest.name+", Locality = "+youngest.locality+", Age = "+youngest.age);
}
}
6. Date And Time API - Date Manipulation
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Solution
{
public static String manipulation(String stringInputDate, int days, int months, int years) {
//Write your code here
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.parse(stringInputDate,df);
LocalDate newd = localDate.plusDays(days).plusMonths(months).plusYears(years);
String date = df.format(newd);
return date;
}
}
public class DateManipulation {
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String stringInputDate = br.readLine();
int days = Integer.parseInt(br.readLine().trim());
int months = Integer.parseInt(br.readLine().trim());
int years = Integer.parseInt(br.readLine().trim());
br.close();
String result = Solution.manipulation(stringInputDate, days, months, years);
System.out.println(result);
}
}
6) B. Date And Time API - Temporal Adjuster
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
class TemporalAdjusterSolution
{
public static String friendShipDay(int inputYear) {
//Write your code here
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.of(inputYear, Month.AUGUST,15);
return date.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY)).format(df).toString();
}
}
public class TemporalAdjuster
{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int inputYear = Integer.parseInt(br.readLine().trim());
br.close();
String result = TemporalAdjusterSolution.friendShipDay(inputYear);
System.out.println("In the year " + inputYear + ", Friendship Day falls on " + result);
}
}
Note: After Completion of Two just Submit to All (No need to write below two codes)
7. Type Annotations
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
class Hospital {
//Write your code for annotations here
// @interface is used to create custom Annotations
// @Target is applicable to only methods and classes.
@Target(ElementType.PARAMETER)
public @interface NonNull{
}
@Target(ElementType.PARAMETER)
public @interface NonNegative{
}
public static String[] addPatientsDetails(@NonNegative String[] input, @NonNull int n, @NonNegative String detailsToBeAdded) {
//Write your code here
String[] res = new String[n+1];
for(int i=0;i<n;i++){
res[i] = input[i];
}
res[n] = detailsToBeAdded;
return res;
}
public static String[] removePatientsDetails(@NonNegative String[] input,@NonNull int n,@NonNegative String patientIdToRemove) {
//Write your code here
ArrayList<String> al = new ArrayList<>();
for(int i= 0;i<n;i++){
String[] temp = input[i].split(" ");
if(!temp[0].equals(patientIdToRemove))
al.add(input[i]);
}
return al.toArray(new String[0]);
}
public static String[] updatePatientsDetails(@NonNegative String[] input,@NonNull int n,@NonNegative String patientIdToUpdate,@NonNegative String patientDetailsToUpdate) {
//Write your code here
for(int i=0;i<n;i++){
String[] temp = input[i].split(" ");
if(temp[0].equals(patientIdToUpdate))
input[i] = patientDetailsToUpdate;
}
return input;
}
}
public class TypeAnnotation {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String input[] = new String[n];
for (int i = 0; i < n; i++) {
input[i] = br.readLine();
}
int query = Integer.parseInt(br.readLine().trim());
if (query == 1) {
String detailsToBeAdded = br.readLine();
String[] result1 = Hospital.addPatientsDetails(input, n, detailsToBeAdded);
for (int i = 0; i < (n+1); i++) {
System.out.println(result1[i]);
}
}
if (query == 2) {
String patientIdToRemove = br.readLine();
String[] result2 = Hospital.removePatientsDetails(input, n, patientIdToRemove);
for (int i = 0; i < (n-1); i++) {
System.out.println(result2[i]);
}
}
if (query == 3) {
String patientIdToUpdate = br.readLine();
String patientDetailsToUpdate = br.readLine();
String[] result3 = Hospital.updatePatientsDetails(input, n, patientIdToUpdate, patientDetailsToUpdate);
for (int i = 0; i < n ; i++) {
System.out.println(result3[i]);
}
}
br.close();
}
}
8.Repeating Annotation :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//Write your code for repeatable annotations here
@Retention (RetentionPolicy.RUNTIME)
@Repeatable (states.class)
@interface Capital{
String state();
String stateCapital();
}
@Retention (RetentionPolicy.RUNTIME)
@interface states{
Capital[] value();
}
@Capital(state = "Tamil Nadu", stateCapital = "Chennai")
@Capital(state = "Kerala", stateCapital = "Thiruvananthapuram")
@Capital(state = "Andhra Pradesh", stateCapital = "Amaravati")
@Capital(state = "Telangana", stateCapital = "Hyderabad")
@Capital(state = "Karnataka", stateCapital = "Bangalore")
@Capital(state = "Maharashtra", stateCapital = "Mumbai")
@Capital(state = "Manipur", stateCapital = "Imphal")
@Capital(state = "Rajasthan",stateCapital = "Jaipur")
@Capital(state = "Arunachal Pradesh", stateCapital = "Itanagar")
@Capital(state = "Assam", stateCapital = "Dispur")
@Capital(state = "Bihar", stateCapital = "Patna")
@Capital(state = "Himachal Pradesh", stateCapital = "Shimla")
@Capital(state = "Haryana", stateCapital = "Chandigarh")
@Capital(state = "Gujarat", stateCapital = "Gandhinagar")
@Capital(state = "Madhya Pradesh", stateCapital = "Bhopal")
@Capital(state = "Meghalaya",stateCapital = "Shillong")
@Capital(state = "Mizoram",stateCapital = "Aizawl")
@Capital(state = "Jharkhand",stateCapital = "Ranchi")
@Capital(state = "Nagaland", stateCapital = "Kohima")
@Capital(state = "Odisha", stateCapital = "Bhubaneswar")
public class RepeatableAnnotation {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(br.readLine().trim());
br.close();
Capital[] states = RepeatableAnnotation.class.getAnnotationsByType(Capital.class);
if (input == 1) {
for (int i = 0; i < 4; i++) {
System.out.println(states[i].state() + " - " + states[i].stateCapital());
}
}
if (input == 2) {
for (int i = 4; i < 8; i++) {
System.out.println(states[i].state() + " - " + states[i].stateCapital());
}
}
if (input == 3) {
for (int i = 8; i < 12; i++) {
System.out.println(states[i].state() + " - " + states[i].stateCapital());
}
}
if (input == 4) {
for (int i = 12; i < 16; i++) {
System.out.println(states[i].state() + " - " + states[i].stateCapital());
}
}
if (input == 5) {
for (int i = 16; i < 20; i++) {
System.out.println(states[i].state() + " - " + states[i].stateCapital());
}
}
}
}
9. JavaScript Engine:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Nashorn {
public static int averageCost(int noOfMonths ,int [] travelCostForMonths)
throws ScriptException {
//Write your code here
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
Integer res = 0;
for(int i: travelCostForMonths){
res+=i;
}
Integer eval = (Integer) nashorn.eval("");
return Math.round((float)res/noOfMonths);
}
}
public class JavaScriptEngine {
public static void main(String[] args) throws IOException, ScriptException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int noOfMonths = Integer.parseInt(br.readLine().trim());
int [] travelCostForMonths = new int [noOfMonths];
for(int i=0; i<noOfMonths; i++)
{
travelCostForMonths[i] = Integer.parseInt(br.readLine().trim());
}
int result = Nashorn.averageCost(noOfMonths, travelCostForMonths);
System.out.println(result);
}
}
If you have any queries, please feel free to ask on the comment section.
If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.
Post a Comment