Last active
March 8, 2019 12:40
-
-
Save Yatharth0045/b52d7de18fe079c14590b79f3c0b64d8 to your computer and use it in GitHub Desktop.
A program for printing the list of students with their roll number, name, marks and grade using predefined functional interfaces.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
import java.util.function.Supplier; | |
class Student { | |
//roll number assigner used by supplier | |
static int rollNoAssigner; | |
//student properties | |
int rollNo; | |
String name; | |
int marks; | |
String grade; | |
//for initializing student with name and marks | |
Student(String name, int marks) { | |
this.name = name; | |
this.marks = marks; | |
} | |
} | |
class FunctionalInterface { | |
public static void main(String[] args) { | |
//Function used to assign grades to students | |
Function<Student, String> getGrade = student -> { | |
String grade = ""; | |
if (student.marks > 90) grade = "A"; | |
else if (student.marks > 80) grade = "B"; | |
else if (student.marks > 70) grade = "C"; | |
else if (student.marks > 60) grade = "D"; | |
else if (student.marks > 50) grade = "E"; | |
else grade = "F"; | |
return grade; | |
}; | |
//Supplier used to supply roll number to the student on FIFO basis | |
Supplier<Integer> assignRollNo = () -> ++Student.rollNoAssigner; | |
//Predicate used to filter students whose marks is greater than 80 | |
Predicate<Integer> filterStudent = marks -> marks >= 80; | |
//Consumer used to print student details | |
Consumer<Student> printStudents = student -> { | |
student.rollNo = assignRollNo.get(); | |
student.grade = getGrade.apply(student); | |
System.out.println("RollNo : " + student.rollNo); | |
System.out.println("Name : " + student.name); | |
System.out.println("Marks : " + student.marks); | |
System.out.println("Grades : " + student.grade + "\n"); | |
}; | |
List<Student> list = Arrays.asList(new Student("divyanshu", 78), new Student("akash", 61), new Student("aditya", 43), new Student("jatin", 94), new Student("yatharth", 88)); | |
for (Student student : list) { | |
if (filterStudent.test(student.marks)) { | |
printStudents.accept(student); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment