You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
Rapply(Tt);
default <V> Function<V, R> compose(Function<? superV, ? extendsT> before)
default <V> Function<T, V> andThen(Function<? superR, ? extendsV> after)
static <T> Function<T, T> identity()
//Map of instructors with name and years of experience//Function which will List<Instructors> and return a Map<String, Integer>//Predicate will return true if instructor has online coursesPredicate<Instructor> p1 = (i) -> i.isOnlineCourses()==true;
Function<List<Instructor>, Map<String,Integer>> mapFunction = (instructors -> {
Map<String,Integer> map = newHashMap<>();
instructors.forEach(instructor -> {
if(p1.test(instructor)) {
map.put(instructor.getName(), instructor.getYearsOfExperience());
}
});
returnmap;
});
System.out.println(mapFunction.apply(Instructors.getAll()));
}
//BiFunction//Bifuction 2 inputs List<Instructors> and second is predicate which will filter if instructor has online//courses and return a map of <String,Integer> string is name and Integer is the years of experiencePredicate<Instructor> p1 = (i) -> i.isOnlineCourses()==true;
BiFunction<List<Instructor>, Predicate<Instructor>, Map<String,Integer>> mapBiFunction =
((instructors, instructorPredicate) -> {
Map<String, Integer> map = newHashMap<>();
instructors.forEach(instructor -> {
if(instructorPredicate.test(instructor)){
map.put(instructor.getName(), instructor.getYearsOfExperience());
}
});
returnmap;
});
System.out.println(mapBiFunction.apply(Instructors.getAll(), p1));
Predicate<Instructor> p2 = ConvertToMethodReferenceExample::greaterThanTenYearsOfExperience;
Instructors.getAll().forEach(instructor -> {
if (p2.test(instructor)){
System.out.println(instructor);
}
});
}
publicstaticbooleangreaterThanTenYearsOfExperience(Instructorinstructor) {
if (instructor.getYearsOfExperience()>10)
returntrue;
returnfalse;
}
VariableScope
staticintl=0;
publicstaticvoidmain(String[] args) {
//Case1//int a =10; //local variable// IntConsumer intConsumer = (a) -> System.out.println(a*10); //Compile time Error {Lambda expression's parameter a cannot redeclare another local variable defined in an enclosing scope. }intb =10; //local variableIntConsumerintConsumer = (a) -> System.out.println(a*10); ////Case 2intk=0;
List<Instructor> instructors = Instructors.getAll();
instructors.forEach(instructor ->{
// System.out.println( k++); //Compile time Error {Local variable k defined in an enclosing scope must be final or effectively final}
});
//Case 3List<Instructor> instructors1 = Instructors.getAll();
instructors1.forEach(instructor ->{
System.out.println( instructor + " " +l); //No error as variable define as class level and its staticl++;
});
}
Stream
Map
//return only instructor names from the instructor listSet<String> instructorNames = Instructors.getAll().stream()
.map(Instructor::getName)
.map(String::toUpperCase)
.collect(Collectors.toSet());
System.out.println(instructorNames);
FlatMap
//Get a list of all the courses which instructors offersSet<String> instructorsCourses = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.collect(Collectors.toSet());
System.out.println(instructorsCourses);
distinct,count,sorted, allmatch and NoneMatch
//count distinct :: Returns the count of elements in this stream.Longcount = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.distinct()
.count();
System.out.println(count);
//distinct Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.List<String> courses = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(courses);
//anymatch, true if any elements of the stream match the provided predicate, otherwise falsebooleanmatch = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.anyMatch(s-> s.startsWith("J"));
System.out.println(match);
// allmatch : true if either all elements of the stream match the provided predicate or the stream is empty, otherwise falsebooleanallmatch = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.allMatch(s-> s.startsWith("J"));
System.out.println(allmatch);
//None mathc : true if either no elements of the stream match the provided predicate or the stream is empty, otherwise falsebooleannonematch = Instructors.getAll().stream()
.map(Instructor::getCourses)
.flatMap(List::stream)
.noneMatch(s-> s.startsWith("J"));
//an Optional describing some element of this stream, or an empty Optional if the stream is empty Optional<T> findAny()
// findFirst :: an Optional describing the first element of this stream, or an empty Optional if the stream is emptyOptional<T> findFirst()
//limit :: Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.Stream<T> limit(longmaxSize)
///Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
listDevs.sort(salaryComparator);
///// max :: Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.Optional<T> max(Comparator<? superT> comparator)
// min: Returns the minimum element of this stream according to the provided Comparator. This is a special case of a reduction.Optional<T> min(Comparator<? superT> comparator)
//skip ::Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.Stream<T> skip(longn)
// sorted :: Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executedStream<T> sorted()
// sorted :: Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.Fororderedstreams, thesortisstable. Forunorderedstreams, nostabilityguaranteesaremade.
Stream<T> sorted(Comparator<? superT> comparator)
ex. customizedsortusingcomparator//retuning all instructors sorted by their nameList<Instructor> list = Instructors.getAll().stream()
.sorted(Comparator.comparing(Instructor::getName).reversed())
.collect(Collectors.toList());
list.forEach(System.out::println);
//
Reduce repeated process for each elements with give operation like csum,multipication, comparison
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
intresults = numbers.stream()
//0 +1 = 1 //10+5= 15 //36+9=45//1 + 2 = 3 //15+ 6= 21//3 + 3 = 6 //21+7 = 28//6+ 4 = 10 //28+8 = 36
.reduce(0,(a,b) -> a +b);
//1 * 1 = 1 //0*1 = 0//1 * 2 = 2 //0*2=0intresults1 = numbers.stream().reduce(1,(a,b) -> a* b);
System.out.println(results);
System.out.println(results1);
Optionalresult2 = numbers.stream().reduce((a, b) -> a + b);
System.out.println("--------");
if(result2.isPresent())
System.out.println(result2.get());
----
//printing the instructor who has the highest years of experienceOptionalinstructor = Instructors.getAll().stream()
.reduce((s1,s2)-> s2.getYearsOfExperience()
>s1.getYearsOfExperience()?s2:s1);
if(instructor.isPresent())
System.out.println(instructor.get());
}
//Implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to //various criteria, etc.// Accumulate names into a ListList<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
// Accumulate names into a TreeSetSet<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));
// Convert elements to strings and concatenate them, separated by commasStringjoined = things.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
// Compute sum of salaries of employeeinttotal = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
// Group employees by departmentMap<Department, List<Employee>> byDept
= employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
// Compute sum of salaries by departmentMap<Department, Integer> totalByDept
= employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));
// Partition students into passing and failingMap<Boolean, List<Student>> passingFailing =
students.stream()
.collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
//mapping //mappingnamesList= Instructors.getAll().stream()
.collect(Collectors.mapping(Instructor::getName, Collectors.toList()));
namesList.forEach(System.out::println);
//Instructors by their years of experienceSystem.out.println("-----------------------------");
System.out.println(Instructors.getAll());
Map<Integer, List<String>> mapYearsOfExperienceAndNames = Instructors.getAll().stream()
.collect(Collectors.groupingBy(Instructor::getYearsOfExperience,
Collectors.mapping(Instructor::getName, Collectors.toList())));
Map<Integer, List<Instructor>> mapYearsOfExperienceAndNames1 = Instructors.getAll().stream()
.collect(Collectors.groupingBy(Instructor::getYearsOfExperience, Collectors.toList()));
Map<Integer, List<Instructor>> mapYearsOfExperienceAndNames2 = Instructors.getAll().stream()
.collect(Collectors.groupingBy(Instructor::getYearsOfExperience));
mapYearsOfExperienceAndNames.forEach((key,value) ->{
System.out.println("key = " + key + " value = " + value);
});
System.out.println("-----------------------------");
//minby() and maxBy()//instructor with minimum years of experienceOptional<Instructor> instructor = Instructors.getAll().stream()
.collect(Collectors.minBy(Comparator.comparing(
Instructor::getYearsOfExperience)));
System.out.println("instructor = " + instructor);
System.out.println("---------------");
instructor = Instructors.getAll().stream()
.min(Comparator.comparing(Instructor::getYearsOfExperience));
System.out.println("instructor = " + instructor);
instructor = Instructors.getAll().stream()
.collect(Collectors.maxBy(Comparator.comparing(
Instructor::getYearsOfExperience)));
System.out.println("instructor = " + instructor);
System.out.println("---------------");
instructor = Instructors.getAll().stream()
.max(Comparator.comparing(Instructor::getYearsOfExperience));
System.out.println("instructor = " + instructor);
//Grouping BY//grouping by instructors by their genderMap<String, List<Instructor>> instructorByGender = Instructors.getAll()
.stream().collect(Collectors.groupingBy(Instructor::getGender));
//grouping by length of string and also checking that the names contains e//and only return those name which has e in itList<String> name = List.of("Sid", "Mike", "Jenny", "Gene", "Rajeev");
Map<Integer, List<String>> result = name.stream()
.collect(Collectors.groupingBy(String::length, Collectors
.filtering(s-> s.contains("e"),Collectors.toList())));
//grouping by length of string and also checking that the names contains e//and only return those name which has e in itList<String> name = List.of("Sid", "Mike", "Jenny", "Gene", "Rajeev");
LinkedHashMap<Integer, List<String>> result = name.stream()
.collect(Collectors.groupingBy(String::length, LinkedHashMap::new, Collectors
.filtering(s-> s.contains("e"),Collectors.toList())));
//partition but return is set instead of listMap<Boolean, Set<Instructor>> partitionSet = Instructors.getAll()
.stream().collect(Collectors.partitioningBy(experiencePredicate,
Collectors.toSet()));
partitionSet.forEach((key,value) -> {
System.out.println("key = " + key + " value: " + value);
});
//A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.static <T> Optional<T> empty()