- Сортировка карты по ключам в Java
- 1. Использование TreeMap
- 2. Использование LinkedHashMap
- 3. Использование Java 8
- Sort a HashMap in Java
- 1. Introduction
- 2. Using a TreeMap
- 3. Using ArrayList
- 3.1. Sort by Key
- 3.2. Sort by Value
- 4. Using a TreeSet
- 4.1. Sort by Key
- 4.2. Sort by Value
- 5. Using Lambdas and Streams
- 5.1. Sort by Key
- 5.2. Sort by Value
- 6. Using Guava
- 7. Summary
Сортировка карты по ключам в Java
В этом посте будут обсуждаться различные методы сортировки карты в Java в соответствии с естественным порядком ее ключей.
1. Использование TreeMap
TreeMap представляет собой реализацию на основе красно-черного дерева Map , который отсортирован в соответствии с естественным порядком его ключей. Мы можем передать несортированную карту в TreeMap конструктор, который затем создаст новую карту дерева, содержащую те же отображения, что и данная карта, но упорядоченные в соответствии с естественным порядком ее ключей.
результат:
Sorted map by keys :
Использование Guava TreeMap :
Библиотека Google Guava также предоставляет TreeMap реализацию, которую мы можем использовать для создания изменяемого пустого TreeMap экземпляр, который сортируется в соответствии с Компаратором, предоставленным во время создания карты. Мы можем пройти мимо Guava Ordering.natural() для естественного порядка ключей.
2. Использование LinkedHashMap
LinkedHashMap представляет собой хэш-таблицу и реализацию связанного списка Map интерфейс с предсказуемым порядком итерации, который представляет собой порядок, в котором ключи были вставлены в карту. Мы можем использовать это свойство для создания копии карты, отсортированной в соответствии с естественным порядком ее ключей.
Идея состоит в том, чтобы создать список ключей, присутствующих на карте, и отсортировать его. Затем мы вставляем пару ключ-значение в пустой LinkedHashMap для каждого ключа в отсортированном списке. Ключи будут сортировать результат LinkedHashMap .
результат:
Sorted map by keys :
Вот эквивалентная версия с использованием Stream API.
результат:
Sorted map by keys :
3. Использование Java 8
Мы также можем использовать Java 8 Stream для сортировки карты по ключам. Ниже приведены шаги:
- Получите поток из заданного представления сопоставлений, содержащихся в карте.
- Отсортируйте поток в естественном порядке ключей, используя Stream.sorted() метод путем передачи компаратора, возвращаемого Map.Entry.comparingByKey() .
- Соберите все отсортированные элементы в LinkedHashMap с использованием Stream.collect() с Collectors.toMap() .
Обратите внимание, что поток — это последовательность элементов, а не последовательность пар ключ/значение. Таким образом, мы не можем построить карту из потока, не указав, как извлекать из него ключи и значения. Java 8 обеспечивает Collectors.toMap() метод для этой цели. Нам нужно использовать перегруженную версию toMap() который возвращает LinkedHashMap вместо HashMap чтобы сохранить отсортированный порядок.
Sort a HashMap in Java
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:
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:
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.
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’re looking for a new Java technical editor to help review new articles for the site.
1. Introduction
In this quick tutorial, we’ll learn how to sort a HashMap in Java.
More specifically, we’ll look at sorting HashMap entries by their key or value using:
2. Using a TreeMap
As we know, keys in TreeMap are sorted using their natural order. This is a good solution when we want to sort the key-value pairs by their key. So the idea is to push all the data from our HashMap into the TreeMap.
To start, let’s define a HashMap and initialize it with some data:
Map map = new HashMap<>(); Employee employee1 = new Employee(1L, "Mher"); map.put(employee1.getName(), employee1); Employee employee2 = new Employee(22L, "Annie"); map.put(employee2.getName(), employee2); Employee employee3 = new Employee(8L, "John"); map.put(employee3.getName(), employee3); Employee employee4 = new Employee(2L, "George"); map.put(employee4.getName(), employee4);
For the Employee class, note that we implemented Comparable:
public class Employee implements Comparable < private Long id; private String name; // constructor, getters, setters // override equals and hashCode @Override public int compareTo(Employee employee) < return (int)(this.id - employee.getId()); >>
Next, we store the entries in the TreeMap by using its constructor:
TreeMap sorted = new TreeMap<>(map);
We can also use the putAll method to copy the data:
TreeMap sorted = new TreeMap<>(); sorted.putAll(map);
And that’s it! To make sure our map entries are sorted by key, let’s print them out:
Annie=Employee George=Employee John=Employee Mher=Employee
As we can see, the keys are sorted in natural order.
3. Using ArrayList
Of course, we can sort the entries of the map with the help of ArrayList. The key difference from the previous method is that we don’t maintain the Map interface here.
3.1. Sort by Key
Let’s load the key set into an ArrayList:
List employeeByKey = new ArrayList<>(map.keySet()); Collections.sort(employeeByKey);
3.2. Sort by Value
Now, what if we want to sort our map values by the id field of the Employee object? We can use an ArrayList for that, too.
First, let’s copy the values into the list:
List employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);
Remember that this works because Employee implements the Comparable interface. Otherwise, we’d need to define a manual comparator for our call to Collections.sort.
To check the results, we print the employeeById:
[Employee, Employee, Employee, Employee]
As we can see, the objects are sorted by their id field.
4. Using a TreeSet
If we don’t want to accept duplicate values in our sorted collection, there’s a nice solution with TreeSet.
First, let’s add some duplicate entries to our initial map:
Employee employee5 = new Employee(1L, "Mher"); map.put(employee5.getName(), employee5); Employee employee6 = new Employee(22L, "Annie"); map.put(employee6.getName(), employee6);
4.1. Sort by Key
To sort the map by its key entries:
SortedSet keySet = new TreeSet<>(map.keySet());
Let’s print the keySet and see the output:
Now we have the map keys sorted without the duplicates.
4.2. Sort by Value
Likewise, for the map values, the conversion code looks like:
SortedSet values = new TreeSet<>(map.values());
[Employee, Employee, Employee, Employee]
As we can see, there are no duplicates in the output. This works with custom objects when we override equals and hashCode.
5. Using Lambdas and Streams
Since Java 8, we can use the Stream API and lambda expressions to sort the map. All we need is to call the sorted method over the map’s stream pipeline.
5.1. Sort by Key
To sort by key, we use the comparingByKey comparator:
map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .forEach(System.out::println);
The final forEach stage prints out the results:
Annie=Employee George=Employee John=Employee Mher=Employee
By default, the sorting mode is ascending.
5.2. Sort by Value
Of course, we can sort by the Employee objects as well:
map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .forEach(System.out::println);
As we can see, the code above prints out a map sorted by the id fields of the Employee objects:
Mher=Employee George=Employee John=Employee Annie=Employee
Additionally, we can collect the results into a new map:
Map result = map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
Note that we collected our results into a LinkedHashMap. By default, Collectors.toMap returns a new HashMap, but as we know, HashMap doesn’t guarantee iteration order, while LinkedHashMap does.
6. Using Guava
Lastly, a library that allows us to sort the HashMap is Guava. Before we begin, it’ll be useful to check our write-up about maps in Guava.
First, let’s declare an Ordering, as we want to sort our map by the Employee’s Id field:
Ordering naturalOrdering = Ordering.natural() .onResultOf(Functions.forMap(map, null));
Now all we need is to use ImmutableSortedMap to illustrate the results:
ImmutableSortedMap.copyOf(map, naturalOrdering);
And once again, the output is a map ordered by the id field:
Mher=Employee George=Employee John=Employee Annie=Employee
7. Summary
In this article, we reviewed a number of ways to sort a HashMap by key or value.
We also learned how to do this by implementing Comparable when the attribute is a custom class.
Finally, as always, the code used in this article can be found over on GitHub.
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: