Java set to list sort

Sorting a HashSet in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

A HashSet is a collection class from the java.util package. This class inherits from the AbstractSet class and implements the Set interface. Furthermore, a HashSet doesn’t preserve the order of elements, hence the need to find ways to sort these elements.

In this quick tutorial, we’ll learn multiple techniques to sort the elements of a HashSet.

2. Using the Collections.sort() Method

The Collections.sort() method sorts collections of objects that implement the java.util.List interface. Therefore, we can convert our HashSet into a List and then sort it using Collections.sort():

HashSet numberHashSet = new HashSet<>(); numberHashSet.add(2); numberHashSet.add(1); numberHashSet.add(4); numberHashSet.add(3); // converting HashSet to arraylist ArrayList arrayList = new ArrayList(numberHashSet); // sorting the list Collections.sort(arrayList); assertThat(arrayList).containsExactly(1, 2, 3, 4);

In the example above, we first copied the elements of our HashSet into an ArrayList. Then, we used our ArrayList as an argument of the Collections.sort() method. Instead of ArrayList, we could also have used LinkedList or Vector.

3. Using a TreeSet

Using this approach, we convert the HashSet to a TreeSet, which is similar to the HashSet except that it stores the elements in ascending order. Therefore, the HashSet elements are put in order when the HashSet is converted to a TreeSet:

HashSet numberHashSet = new HashSet<>(); numberHashSet.add(2); numberHashSet.add(1); numberHashSet.add(4); numberHashSet.add(3); TreeSet treeSet = new TreeSet<>(); treeSet.addAll(numberHashSet); assertThat(treeSet).containsExactly(1, 2, 3, 4);

We can see that using a TreeSet to sort a HashSet is very simple. We only need to create an instance of TreeSet with the HashSet list as an argument.

4. Using the stream().sorted() Method

There’s a concise way to sort a HashSet using the stream().sorted() method of the Stream API. This API, introduced in Java 8, allows us to perform functional operations on a set of elements. Also, it can take objects from different collections and display them in the desired way, depending on the pipeline methods we use.

In our example, we’ll use the stream().sorted() method, which returns a Stream whose elements are sorted in a certain order. It should be noted that since the original HashSet stays unmodified, we need to save the results of the sorting in a new Collection. We will use the collect() method to store the data back into a new HashSet:

HashSet numberHashSet = new HashSet<>(); numberHashSet.add(200); numberHashSet.add(100); numberHashSet.add(400); numberHashSet.add(300); HashSet sortedHashSet = numberHashSet.stream() .sorted() .collect(Collectors.toCollection(LinkedHashSet::new)); assertThat(sortedHashSet).containsExactly(100, 200, 300, 400);

We should note that when we use the stream().sorted() method without a parameter, it sorts the HashSet in the natural order. We can also overload it with a comparator to define a custom sort order.

5. Conclusion

In this article, we discussed how to sort a HashSet in Java using three ways: with the Collections.sort() method, using a TreeSet, and using the stream().sorted() method.

As always, the code snippets are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

How to sort a Set in Java example

There are different versions of Java available with different ways to sort collections of objects. We will be showing examples of how to sort a set of objects or strings alphabetically in Java 8, Java 7 and older versions using comparator.

For this example we will take a Person object and put them all in a set. Each Person have a name and we will sort our collection of Person object alphabetically. It means that we need to implement a comparator which compares Strings.

Let’s assume we can’t implement a compareTo methods inside a Person class. How do we go ahead and compare the objects?

In Java 7 and earlier we would go with overriding the compare method inside a Comparator class. We would than use a compareTo method to compare the strings.

First things first. We can’t sort a Java Set collection by calling Collections.sort() method on a Set. That is because most implementations of Java Set doesn’t have a concept of order. A Set is something without an order by definition in Java.

In order to sort a Java Set we need to convert it to a list first.

Java 7 and earlier

Set items = getPersons(); List personsSorted = new ArrayList<>(); for(Person p : items)

Now that we have an ArrayList, we can use Collections.sort() method and provide our custom anonymous inner Comparator class that compares Person’s names and sorts the list alphabetically.

Collections.sort(personsSorted, new Comparator() < @Override public int compare(Person o1, Person o2) < return o1.getName().compareTo( o2.getName()); >>);

Java 8

In Java 8 there are a lot of new cool features. One of them is streams. It is much easier and more beautiful to convert a Set into a List by using a stream method:

Set items = getPersons(); List personsSorted = items.stream().collect(Collectors.toList());

Another new feature in Java 8 is lambdas. Lambdas are expressions which recognize the object type from the context.

Collections.sort(personsSorted, (o1, o2) -> o1.getName().compareTo(o2.getName()));

The code written in Java 8 is more elegant and is probably faster too.

Источник

Читайте также:  Java рекурсия недостатки и преимущества
Оцените статью