Java 8 coding practice
- Anand Nerurkar
- Jun 2, 2024
- 2 min read
Updated: Jun 4, 2024
list of student rank-between 50 and 100
list of student who stay in karnatake and sort them by name
reverse order
==
find all dept names
==
// unique dept
//all conteact no of students list
student-list of contact - 1 to many so we have to use flatmap as below
// deptwise student list
//dept wise student count
// deptwise student max count
//avg age of male and female student
//groupwise lowest rank
//stunt with 2nd rank
output is c, but it should be l. this is because internally it uses hashmap and hashmap does not preserve insertion order. so we need to use linkedhashmap, this will return l.
nth highest salary-generic code
===
sort the map in asc order-2nd salary
==
sort map in desc
==
//generic method
here we are getting duplicate value for multiple employee, so above code will fail.
so we will use group by as below and see output
we just need key, not entie entry set object as key value pair, we just need key so use below
2nd highest salary
==
make code above generic
==
stream api-for each and filter
==
filter
==
let us take one omore exmaple as below
sort a list
==
if we have custom object in list, then we have to use comparator as below
sort emp based on salary
now with lambda exp
==
how to sort a map with lambda
====
optional
===
3 ways to create optional
1.empty() - return optional.empty object
2.of(x)- if x is null, throws nullpointer exception
3.ofNullable(x) if x is null, return optional.empty
to get value from optional, use get{}.
if optioal is null, then it thows notsuchmethodexception. so we call to check if value is there in optioanl so we use optional isPresent
then use get()
if value is null, then we need to set some default value as below
get customer from a list
==
since there is no customer with pqr email id, so we get above exception. To avoid this, we can set some default value for ex: empty customer object as below
or we can throw our busienss exception as below
max no
==
avg salary of grade a employee
==
java stream excdption handling
===
Comments