Java 8 Stream - How to Sort a Map using lambda | Example | Java Techie

  Рет қаралды 55,774

Java Techie

Java Techie

5 жыл бұрын

This video explain you How to sort a Map in java 8 using lambda expression and stream API even we use Comparator for custom sorting order with stream api - real time example
GitHub:
github.com/Java-Techie-jt/java8
Blogs:
javagyanmantra.wixsite.com/we...
Facebook:
/ 919464521471923
guys if you like this video please do subscribe now and press the bell icon to not miss any update from Java Techie

Пікірлер: 107
@venkatah9847
@venkatah9847 4 жыл бұрын
Thanks for the good explanation. The way examples were explained is awesome. Please continue to do the same.
@omsonschicago5872
@omsonschicago5872 4 жыл бұрын
Thank you so much. Learning from your videos in realtime.
@nidhimanav311
@nidhimanav311 10 ай бұрын
First of all ... I am really thankful to you ... You explained every topic i.e. spring ,java8 or others with explanatory way. It will be quite easy for us to understand the topic. Aapko guru dakshina to dena bnta h 🙏
@Javatechie
@Javatechie 10 ай бұрын
Thank you so much for your word. Glad to hear this keep learning 😃
@sreetmi1918
@sreetmi1918 8 ай бұрын
You are going all the way....Really very useful java material online ...far far better than Institutes who demand money and does no justice in teaching java....Thank you buddy
@Javatechie
@Javatechie 8 ай бұрын
Thank you so much for appreciating it. Keep learning buddy 🙂
@madhurajsingh6558
@madhurajsingh6558 3 жыл бұрын
Best explanation. I learnt a lot from this channel. Thank you so very much 🙏
@Javatechie
@Javatechie 3 жыл бұрын
Good to hear this Madhuraj . Keep learning
@siyedyoussef3202
@siyedyoussef3202 5 жыл бұрын
Great video as always 👍👍👍👍
@francescalabonte4346
@francescalabonte4346 2 жыл бұрын
Absolutely great. thank you.
@ramkethireddy9445
@ramkethireddy9445 4 жыл бұрын
great presentation with realtime examples!! please also cover Optional Class methods
@YanivNahumIPN
@YanivNahumIPN 3 жыл бұрын
Very nice explanation. Regards from Mexico.
@Mohamed-uf5jh
@Mohamed-uf5jh 4 жыл бұрын
Super Great Excellent explain
@vinitgawali1
@vinitgawali1 Жыл бұрын
Thanks you cleared all my doubts
@shubhamthakare5229
@shubhamthakare5229 3 жыл бұрын
Amazing explanation! Please make more video on java 8
@ILuvBilli
@ILuvBilli 5 жыл бұрын
Super Great Excellent
@sreerekhamenon1164
@sreerekhamenon1164 2 жыл бұрын
Good explanation.. thanks
@neutral911
@neutral911 4 жыл бұрын
I've never seen this kind of detailed explanation on rare concepts. Very useful bro... Thank You so much for this video.. Keep it up :)
@Javatechie
@Javatechie 4 жыл бұрын
Thanks KodandaRam . Good to hear this
@vijayr6540
@vijayr6540 4 жыл бұрын
Thankyou nice explanation
@jagrutipatil1020
@jagrutipatil1020 11 ай бұрын
You are genuine...🥰
@taufiquealam4125
@taufiquealam4125 5 жыл бұрын
Great....God bless you.....Could you please make video on difference between interface and abstract class with example in Java 8. Would be highly appreciated.
@lifeofvillageculture628
@lifeofvillageculture628 Жыл бұрын
tq for doing this vedio, its useful.
@raghukg4
@raghukg4 3 жыл бұрын
Hello Java Techie, your explanation is the best ever. My request is that please make a video for Optional class as well. Thanks.
@Javatechie
@Javatechie 3 жыл бұрын
Okay I will do it
@sreddy8141
@sreddy8141 3 жыл бұрын
Sir , found very late, but so helpful, please do videos on data structures and algorithm with same kinda explanation for time and space complexity
@akhileshyaduwanshi6008
@akhileshyaduwanshi6008 2 жыл бұрын
Great Tutorial
@Vishal-8995
@Vishal-8995 4 жыл бұрын
Mr Dependable 🙌🏼
@kishordige4654
@kishordige4654 2 жыл бұрын
Thank you very much!
@gamerauto
@gamerauto 2 жыл бұрын
Let me Zum it guys, thanks man!
@ashmpatel
@ashmpatel 5 жыл бұрын
Nice tutorial
@saurabhkailashchandrapuran8609
@saurabhkailashchandrapuran8609 3 жыл бұрын
Please don't stop here .. make more videos on this type of concept.
@Javatechie
@Javatechie 3 жыл бұрын
Okay we will continue java 8 stream API more features
@aakashkumbhare4399
@aakashkumbhare4399 2 жыл бұрын
Covered most of my doubts
@MuraliM.A.
@MuraliM.A. 29 күн бұрын
Thanks for the video
@Explorewith4x4
@Explorewith4x4 Жыл бұрын
NYC information❤
@abhinandeshwar6335
@abhinandeshwar6335 9 ай бұрын
Best video
@rachanabr
@rachanabr Жыл бұрын
thankyou
@sarojsahoo8763
@sarojsahoo8763 5 жыл бұрын
Instead of using reverse() on comparingByvalue I have used like below .. dataMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEach(System.out::println);
@Javatechie
@Javatechie 5 жыл бұрын
If your value contains some custom object then it won't work .
@RealSlimShady-um6gf
@RealSlimShady-um6gf 8 ай бұрын
@Sarojsahoo yes your code is an alternative to primitive datatype if used. I would be interested in the time complexity of both the approaches.
@yared555
@yared555 3 жыл бұрын
Nice one , I want to see how to debbug in java
@Javatechie
@Javatechie 3 жыл бұрын
Okay I will show with intelij
@RealSlimShady-um6gf
@RealSlimShady-um6gf 8 ай бұрын
This example too you used (int) for Long. If you use actual Long values then this code will break. Very fuzzy logic to use Employee as key and value as Integer
@uxiraj
@uxiraj Жыл бұрын
It took me a while to understand that he used a list to stream list of strings and then map to stream employee objects
@sujithg5873
@sujithg5873 5 жыл бұрын
Can u detailed explanation for method reference
@tiejeevan
@tiejeevan 3 жыл бұрын
I feel this hard as hell even though I practice a lot
@dupindersingh1599
@dupindersingh1599 3 жыл бұрын
When will you upload more videos related to Java Stream API
@tiwarybaba
@tiwarybaba 2 жыл бұрын
sorry for the lame question...but we're using the entrySet() with employeeMap just to get it in list form(Map.Entry), so that we can use it for sorting, like entry.getKey()... right?
@Javatechie
@Javatechie 2 жыл бұрын
No you need to use Map.Entry.comparingByKey()
@tiwarybaba
@tiwarybaba 2 жыл бұрын
@@Javatechie that I understood...my question is with the Map reference (employeeMap) in the example, u used employeeMap.entrySet()...why did u did that?
@lifeisbeautiful230
@lifeisbeautiful230 5 ай бұрын
Line number 21gives Cannot infer type arguments for ArrayList error. I am using Java 17.
@Javatechie
@Javatechie 5 ай бұрын
Share the code snippet please
@lifeisbeautiful230
@lifeisbeautiful230 5 ай бұрын
@@Javatechie //THIS LINE IS HAVING ERROR "gives Cannot infer type arguments for ArrayList " //I am using Java 17 List entries = new ArrayList(imap.entrySet()); Collections.sort(entries, new Comparator() { @Override public int compare(Entry o1, Entry o2) { // TODO Auto-generated method stub return o1.getKey().compareTo(o2.getKey()); } }); for(Entry entry:entries) { System.out.println(entry.getKey()+""+entry.getValue()); } }
@acchutdevkule7841
@acchutdevkule7841 3 жыл бұрын
Hello, how can wirite program for passing employee object in hashmap as value and want to sort by value based on employee id?
@Javatechie
@Javatechie 3 жыл бұрын
I already explained it just change syntax to comparingByValue instead of comparingByKey
@geetha.egowda8674
@geetha.egowda8674 2 жыл бұрын
I am doing the same way, but i am getting an error like LinkedHashMap cannot be cast to class ProcessFlow (POJO) (LinkedHashMap is in java.base of loader 'bootstrap' ; ProcessFlow is in unnamed module of loader 'app'). I am stuck, can you please help here
@abhinavjain5584
@abhinavjain5584 11 ай бұрын
Time stem 6:54 i try to add reversed() method but it gives error
@pankajpandey6298
@pankajpandey6298 Жыл бұрын
Hi Sir can you tell how to collect map object using stream instead of sysout?
@Javatechie
@Javatechie Жыл бұрын
Just use collect(Collectors.toList()) instead of foreach
@pankajpandey6298
@pankajpandey6298 Жыл бұрын
@@Javatechie thankyou sir
@sreddy8141
@sreddy8141 Ай бұрын
i have tried the same but its not sorting not sure whats the issue
@krishnamohan5771
@krishnamohan5771 2 ай бұрын
can we remove the comparator in the treemap constructor if we are sorting by streams
@Javatechie
@Javatechie 2 ай бұрын
Yes comparator not required to explicitly added in constructor if you are using stream
@krishnamohan5771
@krishnamohan5771 2 ай бұрын
@@Javatechie its giving class cast exception if no comparator is provided for tree map constructor
@swacharahman5084
@swacharahman5084 Жыл бұрын
Hello, what to do if the map's key and value are both integer?
@Javatechie
@Javatechie Жыл бұрын
How does it matter? Based on either key or value you can easily sort right
@swacharahman5084
@swacharahman5084 Жыл бұрын
@@Javatechie yes, i figured that out. btw wonderful video,THANK YOU
@user-uf7uq3wg3j
@user-uf7uq3wg3j 11 ай бұрын
sir ClassCastException is coming when i am not passing lamda exp in TreeSet Constructor . when we are sorting using streams why i need to still pass lamda exp in TreeSet Constructor???
@Javatechie
@Javatechie 11 ай бұрын
Lambda internally uses HashSet not TreeSet buddy
@user-uf7uq3wg3j
@user-uf7uq3wg3j 11 ай бұрын
@@Javatechie sir Sorry,i didn't understand what you are saying 😅😅
@Javatechie
@Javatechie 11 ай бұрын
Share me the code where you are getting exception
@user-uf7uq3wg3j
@user-uf7uq3wg3j 11 ай бұрын
@@Javatechie public class SortMap2 { public static void main(String[] args) { Map employeeMap = new TreeMap(); employeeMap.put(new Employee(176, "Roshan", "IT", 600000), 60); employeeMap.put(new Employee(388, "Bikash", "CIVIL", 900000), 90); employeeMap.put(new Employee(470, "Bimal", "DEFENCE", 500000), 50); employeeMap.put(new Employee(624, "Sourav", "CORE", 400000), 40); employeeMap.put(new Employee(284, "Prakash", "SOCIAL", 1200000), 120); System.out.println(employeeMap); employeeMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.comparing(Employee::getSalary).reversed())) .forEach(System.out::println); } }
@jeet2450
@jeet2450 4 жыл бұрын
Could you plese help me to sort like this Map using java 8
@Javatechie
@Javatechie 4 жыл бұрын
Jeet send me the sample collection and Expected order please
@jeet2450
@jeet2450 4 жыл бұрын
@@Javatechie Map [aaaaaa, rrt]=[TestDTO(modelCode=aaaaaa, modelTypeCode=rrt, colourCode=389...), TestDTO(modelCode=aaaaaa, modelTypeCode=rrt, colourCode=30..), TestDTO(modelCode=aaaaaa, modelTypeCode=rrt, colourCode=308.) [zkaka, rrt]=[TestDTO(modelCode=zkaka, modelTypeCode=rrt, colourCode=389...), TestDTO(modelCode=zkaka, modelTypeCode=rrt, colourCode=30..), TestDTO(modelCode=zkaka, modelTypeCode=rrt, colourCode=667.) [ckaka, rrt]=[TestDTO(modelCode=ckaka, modelTypeCode=rrt, colourCode=389...), TestDTO(modelCode=ckaka, modelTypeCode=rrt, colourCode=30..), TestDTO(modelCode=ckaka, modelTypeCode=rrt, colourCode=667.) Modelcode and modelTypeCode is same in the key. Key--> [aaaaaa, rrt] based on key please sort the map.
@sujitkumarmishra8004
@sujitkumarmishra8004 10 ай бұрын
Hi Basant, map.entrySet().stream().sorted(Map.Entry.comparingByKey().reversed()).forEach(System.out::println); In the above line, reversed() method is not working. I am getting compile time error here in this case. But when I am trying the below approach, it's working. map.entrySet().stream().sorted(Entry. comparingByKey().reversed()).forEach(System.out::println); Please suggest exactly in which way we have to try?
@Javatechie
@Javatechie 10 ай бұрын
We need to use collections.reverse please check out my java 8 programming questions i have explained there
@RealSlimShady-um6gf
@RealSlimShady-um6gf 8 ай бұрын
13.05 also used reversed. Didn't understand the logic of using String and Integer. Basant used String and Integer initially just to explain and later he shifted to a custom Employee class which is debatable
@ramesh_p
@ramesh_p 6 ай бұрын
@@Javatechie This may work by adding explicitly the type of comparator returned by comparingByKey(). Something like this map.entrySet().stream().sorted(Map.Entry.comparingByKey().reversed())
@kanagujagan509
@kanagujagan509 3 жыл бұрын
How to sort more than one properties.?
@rahulben4762
@rahulben4762 5 жыл бұрын
entries.stream().sorted(Map.Entry.comparingByKey().reversed()).forEach(System.out::println); is not working at 6:53 please help
@Javatechie
@Javatechie 5 жыл бұрын
Is reversed method not applicable for sorted .I believe I show it .if not let me know
@rahulben4762
@rahulben4762 5 жыл бұрын
​@@Javatechie employeeMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.comparing(Employee::getDept).reversed())).forEach(System.out::println); So Basant Map.Entry.ComparingByKey is working but Map.Entry.ComparingByValue in combination of reversed() method. Thank you in advance
@Javatechie
@Javatechie 5 жыл бұрын
@@rahulben4762 its working dude please try with same syntax which i share in video employeeMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparing(Employee::getDept).reversed())) .forEach(System.out::println);
@Javatechie
@Javatechie 5 жыл бұрын
@@rahulben4762 for value we can try below poc , i didn't find any straight forward approach employeeMap.entrySet() .stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .collect( toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
@venuvamsi5344
@venuvamsi5344 4 жыл бұрын
Sir,If we have to use object as key in hash map then Do we need to overide equals and hashcode? If yes,what are problems do we face without overiding?
@krishnamohan5771
@krishnamohan5771 2 ай бұрын
why you are using treemap here..any reason
@Ankit-vp7nt
@Ankit-vp7nt 4 жыл бұрын
Comparing by value how to do ...
@Javatechie
@Javatechie 4 жыл бұрын
Already explained in this video please have a look
@Ankit-vp7nt
@Ankit-vp7nt 4 жыл бұрын
@@Javatechie Map map= EmpDataBase.getEmployee(); //traditional apporch List entries=new ArrayList(map.entrySet()); Collections.sort(entries,(o1,o2) -> o1.getValue().getId()-o2.getValue().getId()); for(Entry entry:entries) { System.out.println(entry); } Bro in this way working comparing by value
@Ankit-vp7nt
@Ankit-vp7nt 4 жыл бұрын
But using stream map.entrySet().stream().sorted(Map.Entry.comparingByValue(new Comparator() { @Override public int compare(Entry o1, Entry o2) { return o1.getValue().getId()-o2.getValue().getId(); } })); I stuck
@Ankit-vp7nt
@Ankit-vp7nt 4 жыл бұрын
Help me bro
@Ankit-vp7nt
@Ankit-vp7nt 4 жыл бұрын
Bro working just Chech it correct or not map.entrySet().stream().sorted((o1,o2) -> o1.getValue().getId()-o2.getValue().getId()).forEach(System.out::println);
@AmritAgarwal07
@AmritAgarwal07 3 жыл бұрын
HashMap keyValuePairs = new HashMap(); var valuesList = keyValuePairs.Where(x => x.Value == keyValuePairs.Values.Max()).Select(v => v.Key).OrderBy(y => y).ToList();
@AmritAgarwal07
@AmritAgarwal07 3 жыл бұрын
can you tell me the equivalent Java stream code for this?
@Javatechie
@Javatechie 3 жыл бұрын
Let me check
@AmritAgarwal07
@AmritAgarwal07 3 жыл бұрын
@@Javatechie ok
@alldemb9496
@alldemb9496 2 жыл бұрын
// Sort map by values using stream Map myMap1 = new HashMap(); myMap1.put("a", 1); myMap1.put("d", 2); myMap1.put("b", 3); myMap1.put("f", 4); myMap1.put("h", 0); myMap1.put("g", 4); myMap1.put("e", 8); Map employeeMap = new HashMap(); employeeMap.put(5, new Employee(1, "Tom", 20)); employeeMap.put(9, new Employee(9, "Robert", 45)); employeeMap.put(1, new Employee(100, "Gita", 29)); employeeMap.put(6, new Employee(15, "Tara", 25)); employeeMap.put(3, new Employee(3, "Bal", 29)); employeeMap.put(2, new Employee(22, "Tarun", 39)); // Sorting using comparator //myMap1.entrySet().stream().sorted((a,b)->a.getKey().compareTo(b.getKey())).forEach(System.out::println); //myMap1.entrySet().stream().sorted((a,b)-> a.getValue()-b.getValue()).forEach(System.out::println); // Reverse order //myMap1.entrySet().stream().sorted((a,b)->b.getKey().compareTo(a.getKey())).forEach(System.out::println); //myMap1.entrySet().stream().sorted((a,b)-> b.getValue()-a.getValue()).forEach(System.out::println); // Objects //By age //employeeMap.entrySet().stream().sorted((a,b)->a.getValue().getAge()-b.getValue().getAge()).forEach(System.out::println);; //By name //employeeMap.entrySet().stream().sorted((a,b)->a.getValue().getName().compareTo(b.getValue().getName())).forEach(System.out::println);
@kishyash1
@kishyash1 2 жыл бұрын
Hi Java Technie map.entrySet().stream().sorted(Map.Entry.comparingByKey().reversed()).forEach(System.out::println); above code showing compilation error because of reversed method above map is string as key and int as value
@RN-jo8zt
@RN-jo8zt Жыл бұрын
Do we really need stream for sorting? I can write like below studentslist.sort( (o1, o2) -> o1.getFirstName().compareTo(o2.getFirstName()));
@Javatechie
@Javatechie Жыл бұрын
Why lambda and functional interface introduced?
@RN-jo8zt
@RN-jo8zt Жыл бұрын
I rhink we can use it on collection framework for better performance and code will be short and flexible
@Javatechie
@Javatechie Жыл бұрын
Correct when I am doing sorting here . I am just doing it for collections of objects
Java 8 Streams | map () & flatMap() Example | JavaTechie
15:37
Java Techie
Рет қаралды 206 М.
Homemade Professional Spy Trick To Unlock A Phone 🔍
00:55
Crafty Champions
Рет қаралды 59 МЛН
MEU IRMÃO FICOU FAMOSO
00:52
Matheus Kriwat
Рет қаралды 34 МЛН
JDK8 Stream API (Complete Course) | By Mr. Suman
2:27:19
SreenuTech
Рет қаралды 21 М.
Stream API in Java
26:04
Telusko
Рет қаралды 279 М.
Master Golang with Interfaces
21:54
Kantan Coding
Рет қаралды 7 М.
Streams API Tutorial in Java 8+
31:38
Daily Code Buffer
Рет қаралды 86 М.
New Java Version 22 - The 3 Best New Features You'll ACTUALLY Use
13:15
Coding with John
Рет қаралды 95 М.
Simple maintenance. #leddisplay #ledscreen #ledwall #ledmodule #ledinstallation
0:19
LED Screen Factory-EagerLED
Рет қаралды 3,3 МЛН
ПОКУПКА ТЕЛЕФОНА С АВИТО?🤭
1:00
Корнеич
Рет қаралды 3,2 МЛН
Best mobile of all time💥🗿 [Troll Face]
0:24
Special SHNTY 2.0
Рет қаралды 527 М.
APPLE совершила РЕВОЛЮЦИЮ!
0:39
ÉЖИ АКСЁНОВ
Рет қаралды 4,3 МЛН