top of page

Java 8 coding practice

  • Writer: Anand Nerurkar
    Anand Nerurkar
  • Jun 2, 2024
  • 2 min read

Updated: Jun 4, 2024

ree

list of student rank-between 50 and 100

ree

list of student who stay in karnatake and sort them by name

ree

reverse order

==

ree

find all dept names

==

ree

// unique dept

ree

//all conteact no of students list


ree

student-list of contact - 1 to many so we have to use flatmap as below

ree

// deptwise student list


ree

//dept wise student count

ree

// deptwise student max count

ree

//avg age of male and female student

ree

//groupwise lowest rank

ree

//stunt with 2nd rank

ree

ree

ree
ree
ree
ree
ree
ree
ree

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.

ree
ree
ree
ree

ree
ree
ree
ree
ree

nth highest salary-generic code

===

ree

sort the map in asc order-2nd salary

==

ree
ree

sort map in desc

==

ree
ree

//generic method

ree

ree
ree

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

ree
ree

we just need key, not entie entry set object as key value pair, we just need key so use below

ree
ree

2nd highest salary

==

ree
ree

make code above generic

==

ree

stream api-for each and filter

==

ree
ree
ree
ree
ree

filter

==

ree
ree

let us take one omore exmaple as below

ree
ree
ree

sort a list

==

ree

if we have custom object in list, then we have to use comparator as below

sort emp based on salary

ree
ree

now with lambda exp

==

ree
ree
ree

how to sort a map with lambda

====

ree
ree
ree
ree
ree
ree
ree
ree

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

ree
ree

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

ree

get customer from a list

==

ree
ree
ree

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

ree

or we can throw our busienss exception as below

ree
ree
ree
ree
ree

max no

==

ree
ree
ree

avg salary of grade a employee

==

ree
ree
ree

java stream excdption handling

===

ree
ree

 
 
 

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
  • Facebook
  • Twitter
  • LinkedIn

©2024 by AeeroTech. Proudly created with Wix.com

bottom of page