Тёмный

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

Java Techie
Подписаться 169 тыс.
Просмотров 55 тыс.
50% 1

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

Наука

Опубликовано:

 

29 мар 2019

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 107   
@omsonschicago5872
@omsonschicago5872 4 года назад
Thank you so much. Learning from your videos in realtime.
@venkatah9847
@venkatah9847 4 года назад
Thanks for the good explanation. The way examples were explained is awesome. Please continue to do the same.
@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
@nidhimanav311
@nidhimanav311 9 месяцев назад
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 9 месяцев назад
Thank you so much for your word. Glad to hear this keep learning 😃
@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
@francescalabonte4346
@francescalabonte4346 2 года назад
Absolutely great. thank you.
@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 🙂
@siyedyoussef3202
@siyedyoussef3202 5 лет назад
Great video as always 👍👍👍👍
@YanivNahumIPN
@YanivNahumIPN 3 года назад
Very nice explanation. Regards from Mexico.
@ramkethireddy9445
@ramkethireddy9445 4 года назад
great presentation with realtime examples!! please also cover Optional Class methods
@Mohamed-uf5jh
@Mohamed-uf5jh 4 года назад
Super Great Excellent explain
@vinitgawali1
@vinitgawali1 Год назад
Thanks you cleared all my doubts
@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.
@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
@ILuvBilli
@ILuvBilli 5 лет назад
Super Great Excellent
@shubhamthakare5229
@shubhamthakare5229 3 года назад
Amazing explanation! Please make more video on java 8
@sreerekhamenon1164
@sreerekhamenon1164 2 года назад
Good explanation.. thanks
@vijayr6540
@vijayr6540 4 года назад
Thankyou nice explanation
@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
@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
@jagrutipatil1020
@jagrutipatil1020 11 месяцев назад
You are genuine...🥰
@lifeofvillageculture628
@lifeofvillageculture628 Год назад
tq for doing this vedio, its useful.
@kishordige4654
@kishordige4654 2 года назад
Thank you very much!
@akhileshyaduwanshi6008
@akhileshyaduwanshi6008 2 года назад
Great Tutorial
@aakashkumbhare4399
@aakashkumbhare4399 2 года назад
Covered most of my doubts
@gamerauto
@gamerauto 2 года назад
Let me Zum it guys, thanks man!
@Vishal-8995
@Vishal-8995 3 года назад
Mr Dependable 🙌🏼
@ashmpatel
@ashmpatel 5 лет назад
Nice tutorial
@MuraliM.A.
@MuraliM.A. 17 дней назад
Thanks for the video
@Explorewith4x4
@Explorewith4x4 Год назад
NYC information❤
@abhinandeshwar6335
@abhinandeshwar6335 9 месяцев назад
Best video
@rachanabr
@rachanabr Год назад
thankyou
@sujithg5873
@sujithg5873 5 лет назад
Can u detailed explanation for method reference
@yared555
@yared555 3 года назад
Nice one , I want to see how to debbug in java
@Javatechie
@Javatechie 3 года назад
Okay I will show with intelij
@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.
@dupindersingh1599
@dupindersingh1599 3 года назад
When will you upload more videos related to Java Stream API
@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
@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
@tiejeevan
@tiejeevan 3 года назад
I feel this hard as hell even though I practice a lot
@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?
@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
@abhinavjain5584
@abhinavjain5584 11 месяцев назад
Time stem 6:54 i try to add reversed() method but it gives error
@sreddy8141
@sreddy8141 Месяц назад
i have tried the same but its not sorting not sure whats the issue
@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()); } }
@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
@kanagujagan509
@kanagujagan509 3 года назад
How to sort more than one properties.?
@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
@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
@user-uf7uq3wg3j
@user-uf7uq3wg3j 10 месяцев назад
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 10 месяцев назад
Lambda internally uses HashSet not TreeSet buddy
@user-uf7uq3wg3j
@user-uf7uq3wg3j 10 месяцев назад
@@Javatechie sir Sorry,i didn't understand what you are saying 😅😅
@Javatechie
@Javatechie 10 месяцев назад
Share me the code where you are getting exception
@user-uf7uq3wg3j
@user-uf7uq3wg3j 10 месяцев назад
@@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); } }
@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
@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())
@jeet2450
@jeet2450 3 года назад
Could you plese help me to sort like this Map using java 8
@Javatechie
@Javatechie 3 года назад
Jeet send me the sample collection and Expected order please
@jeet2450
@jeet2450 3 года назад
@@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.
@krishnamohan5771
@krishnamohan5771 2 месяца назад
why you are using treemap here..any reason
@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?
@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 Год назад
// 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
Далее
Sort HashMap By Value Java8
6:17
Просмотров 3,7 тыс.
Java 8 Stream API  : Streams Filter & Map Operations
15:35
Lambda Expressions in Java - Full Simple Tutorial
13:05
ForEach Method in Java
14:06
Просмотров 39 тыс.
Face ID iPhone 14 Pro
0:59
Просмотров 15 тыс.
Неразрушаемый смартфон
1:00
Просмотров 897 тыс.