EP55 – How to Sort with Streams in Java
Description
GitHub link here: https://github.com/tp02ga/FunWithStreams
In this episode we'll talk about how to sort a stream of objects using the “.sorted()” function.
We'll also talk about the differences between using a stream to sort vs using something like Collections.sort(), which has been available since Java v1.2
Episode Transcript
0:09
Welcome to the coders campus podcast, where you'll learn how to code from one of the best teachers in the industry. Whether you're an absolute beginner or a seasoned pro, the coders campus podcast will teach you what you need to know, to master the art of programming. And now, your host, Trevor page.
0:28
All right, ladies and gentlemen, welcome to this next episode of the podcast. It has hit episode number 55. Now, always a pleasure to have you in well in your earbuds and me sitting in front of this microphone in my office. So yes, always a pleasure. Let's dive into the topic for today, which will be a continuation of the theme that we've been working on, which is streams. In this one, I want to dive into sorting, which is not too crazy. There's not too much going on here with sorting in streams, but it's an important thing to know about. And that there's time. If it doesn't take too much, then we can dive on into the next topic, which you never know. I'll see how it looks once we get there. So as always, this lesson or episode of you will is brought to you by the coders campus boot camp. If you are looking to get a job as a coder, we are constantly improving the boot camp, we are constantly bringing in new talent and churning out really the next generation of great coders. And I couldn't be more proud of the students who are going through the curriculum right now. So to all you students who might be listening to this, because I know you are. If you're still in the boot camp, keep keep on truckin. I know, it's tough, I know it's hard. If you have come out the other end, congratulations. And I look forward to seeing you in your future career. So if you're interested, check it out. coaters campus.com/bootcamp to check out all of the details there. So let's go into streams with respect to sorting. So before we had streams, sorting was done or achieved via one of two means in the world of Java, you can either sort using comparable or a comparator. I never know how to pronounce that word, I like to pronounce the tour at the end. So in the world of streams and sorting, it's much the same. So if you're using comparable comparable is an interface that you can implement yourself if you have access to the other class that you want to be sorting. So if you have control over it, meaning if you have created an object, and you wish to sort those objects, you can implement comparable within your objects class, and implement the compare to method that it forces you to override. In our example, we could have done that, but I'm just doing a comparator instead. Because, well, it's it's you can see all the code in front of us. So it's just a little bit easier to get the point across when use a comparator. But this is really, you know, six of one half dozen, or the other is the expression meaning it doesn't really matter which one that you go with, because it's still sorting, sorting is still sorting. So yeah, and this one, we're gonna be using competitors. And that's just like, you can see the code in front of you. So when you did it, quote, unquote, the old way, meaning before you had streams, how did you accomplish sorting? Well, in this example, I'm going to be having I'm going to have a bunch of user objects, the users will have the common things that users always have username, password, but it's also going to have a, which call it
3:36
a last login date. Meaning that this particular class called user has a property called last login date, which is just a date that represents the last time that that user logged in. Now, we're not going to talk about how to implement that functionality that is outside the scope of this conversation, we're just going to assume that that is already done. And we are just handed the data. So we're just handed a collection of these users that has the data prefilled. Now if you're following along with the code that I am making available, you can check it out. Whereas it coderscampus.com/55, I guess will redirect you to this particular entry, or post or whatever you want to call it. And I will have a repo GitHub repo there, where you can check out the code that we're talking about. In any case, if you're following along with the code, then great. If you're not then no worries, I'll do my best as I always try to do to explain it. But yeah, we have a user and we will have or rather a collection of users and the users will have the data pre populated so the code that I will present you with. I just wrote some code to generate users, so it just will randomly generate users with a random username and a random password and random dates. That represent the last time that they've logged in. Basically, I just look at what today is, when you're writing the code, it looks at what today is, that's the maximum day that you can, you know, randomly generate. And the minimum day is like 90 days ago. So no matter when you run this code, whether it's you know, today when I'm recording this episode, or you know, sometime in the future, it should always work. Cool. So it'll generate dates. For last logins, it'll generate usernames and passwords and everything, and it'll generate a list of users. And how do we then go about, you know, accomplishing our sort? And how are we sorting? So for these ones, I want to sort the users by the last login date, so I want to see a list of the ones who, you know, just a list of the sorted users by when they last logged in. But I also want to filter out any users that haven't logged in, you know, in the last 30 days, or prior to 30 days ago, I should say. So what that means is anyone who's logged in 31 days, or are further out in the past, I just don't want to see them. Only the users that I want to see recently who've logged in, those are the ones I want to see. And I want to see them in the sorted list. Okay. Again, why? I don't know, I just sort of picked out of thin air. That's, you know, who knows, maybe there's a business requirement somewhere that says I want to see a sorted list of the most recently logged in users? I don't know, maybe that's useful to someone. So that's what we're going for here. But how do we accomplish it? Well, without streams, again, it's going to be more verbose, right? Without streams, you're first going to have to filter the list based on the getting rid of the people who have logged in more than 30 days ago. So I have some code there to filter lists. We've talked about filtering before. Without streams, you just have to iterate through them, you need to create a new collection. While you iterate through the existing collection, you will insert into the new collection, all of the entries that meet your filtering criteria. Okay, that's essentially how you get it done. I don't want to go into that we've already talked about that concept before. So we will filter our list create a new one, a new filtered list with just the ones who have logged in no more than 30 days ago. So now we have our filtered list. And how do we sort a list? Well, you can use collections dot sort, this is something that was has been available for a little while I forget when it was created since 1.2. So Java 1.2. So for quite a while you've been able to do collections dot sort. And collections dot sort takes an input of a list. So you pass in the list, but then it's not going to know how to sort that list. Because it's it's a, it's a custom type, right, we have created the user class, the user type, so it's not going to know how to sort it. So you need to tell it how to sort it either using comparable that we talked about before, or using comparator. So we can instantiate a new comparator, which is the way I'm going here, instantiate instantiate a new comparator, which forces you to override the Compare method. And then you can put the code in to compare the log in the last logon dates for all the users. Okay, I don't really want to go into all the code there that's needed. But suffice it to say, it's, I don't know, a few lines of code, right. So in total, we're talking about what 1234567 ish lines of code here to accomplish everything that I've talked about. And then you can output you know, your list your filtered list of users. So that's sort of the old way of doing it. Now, there's not there's not that there is anything wrong with that. It's just a little bit verbose. You just have to spell it all out. And it's not very sexy, it's not very, you know, it's just not easy to read, so to speak, right? That's, we've talked about this before, streams, makes code much easier to read, in my opinion. And in the opinion of like all the developers who've ever used streams. So yeah, that's how you accomplish that task. Now one side effect that happens with the collections dot sort method, which is the old way of sorting. Again, I keep I say old way, only to say that this is not using streams. So this is the non stream way to sort you can leverage collections dot sort. There are certainly other ways to sort this is just one of them. The side effects using collections dot sort is it will mutate the collection, mutate the list that you are giving to the collections dot sort function. So it will actually mutate that list, right? So this is a this is called side effects. This is where, if you're not aware that this is happening, it can cause




