Java map получить максимальное значение

Найти самый большой номер в HashSet / HashMap Java

Я хотел бы найти наибольшее число в HashSet и HashMap. Скажем, у меня есть номер [22,6763,32,42,33] в моем HashSet, и я хочу найти наибольшее число в моем текущем HashSet. Как бы я это сделал? и то же самое для HashMap. Надеюсь, ты сможешь мне помочь. Спасибо.

8 ответов

Вы можете использовать Collections.max(Collection) , чтобы найти максимальный элемент из любой коллекции. Аналогично, для HashMap вы можете использовать тот же метод на keySet() или values() , в зависимости от того, хотите ли вы максимальный ключ или максимальное значение.

Кроме того, если вы хотите как таковой, вы можете использовать TreeSet и TreeMap вместо этого хранит элементы в упорядоченном порядке клавиш.

 int max = Collections.max(set); int maxKey = Collections.max(map.keySet()); int maxValue Collections.max(map.values()); 

Если вы вынуждены использовать HashSet / HashMap , вам нужно отсканировать весь HashSet / HashMap , чтобы найти максимум. Библиотечные функции, такие как Collections.max() , будут делать это следующим образом.

Если вы хотите O(1) извлечь максимум, и вы можете изменить тип используемой коллекции, используйте отсортированный набор/карту (например, TreeSet / TreeMap ).

O (1) работает только на ключах карты; для значений сначала нужно создать отдельную коллекцию, так что опять O (n), с очень плохим постоянным фактором.

Также обратите внимание, что TreeSet становится дороже для вставки и удаления. Поэтому мудро выбирайте правильную реализацию

Set values = new HashSet() >; int maxValue = Integer.MIN_VALUE; for (int value : values) < if (value >maxValue) < maxValue = value; >> 
Map values = new HashMap() >; int maxValue = Integer.MIN_VALUE; for (int value : values.values()) < if (value >maxValue) < maxValue = value; >> 

Ужасный способ инициализации HashMap только для этой простой цели должен быть создан новый класс. Я ненавижу это каждый раз, когда вижу в коде, с которым работаю.

Читайте также:  Создание двумерной матрицы java

То, что я написал выше, создает новый класс только для создания карты с несколькими элементами. Это очень медленно (есть тесты на stackoverflow).

Примечание. Если вы хотите найти наибольшее значение в Map, попробуйте maxEntry.get(). GetValue() вместо maxEntry.get(). GetKey().

1. Использование Stream

public > V maxUsingStreamAndLambda(Map map) < Optional maxEntry = map.entrySet() .stream() .max((Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue()) ); return maxEntry.get().getKey(); > 

2. Использование Collections.max() с лямбда-выражением

public > V maxUsingCollectionsMaxAndLambda(Map map) < EntrymaxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.getKey(); > 

3. Использование потока со ссылкой на метод

public > V maxUsingStreamAndMethodReference(Map map) < Optional maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Map.Entry::getValue)); return maxEntry.get() .getKey(); > 

4. Использование Collections.max()

public > V maxUsingCollectionsMax(Map map) < EntrymaxEntry = Collections.max(map.entrySet(), new Comparator() < public int compare(Entrye1, Entry e2) < return e1.getValue() .compareTo(e2.getValue()); >>); return maxEntry.getKey(); > 

5. Использование простой итерации

public > V maxUsingIteration(Map map) < Map.EntrymaxEntry = null; for (Map.Entry entry : map.entrySet()) < if (maxEntry == null || entry.getValue() .compareTo(maxEntry.getValue()) >0) < maxEntry = entry; >> return maxEntry.getKey(); > 

Источник

Finding the Highest Value in a Java Map

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:

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

1. Overview

In this quick tutorial, we’ll explore various ways to find the maximum value in a Java Map. We’ll also see how new features in Java 8 have simplified this operation.

Before we begin let’s briefly recap how objects are compared in Java.

Typically objects can express a natural ordering by implementing the method compareTo() from the Comparable interface. However, an ordering other than natural ordering can be employed through a Comparator object. We’ll see these in more details as we go on.

2. Before Java 8

Let’s start first exploring how can we find the highest value without Java 8 features.

2.1. Using Simple Iteration

Using iteration we could simply go through all the entries of a Map to pick the highest value, storing the current highest in a variable:

public > V maxUsingIteration(Map map) < Map.EntrymaxEntry = null; for (Map.Entry entry : map.entrySet()) < if (maxEntry == null || entry.getValue() .compareTo(maxEntry.getValue()) >0) < maxEntry = entry; >> return maxEntry.getValue(); >

Here, we’re also making use of Java generics to build a method that can be applied to different types.

2.2. Using Collections.max()

Now let’s see how the utility method max() in the Collections class can save us from writing a lot of this ourselves:

public > V maxUsingCollectionsMax(Map map) < EntrymaxEntry = Collections.max(map.entrySet(), new Comparator() < public int compare(Entrye1, Entry e2) < return e1.getValue() .compareTo(e2.getValue()); >>); return maxEntry.getValue(); >

In this example, we’re passing a Comparator object to max() which can leverage the natural ordering of the Entry values through compareTo() or implement a different ordering altogether.

3. After Java 8

Java 8 features can simplify our attempt above to get the max value from a Map in more ways than one.

3.1. Using Collections.max() with a Lambda Expression

Let’s begin by exploring how lambda expressions can simplify the call to Collections.max():

public > V maxUsingCollectionsMaxAndLambda(Map map) < EntrymaxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.getValue(); >

As we can see here, lambda expressions save us from defining the full-fledged functional interface and provide a concise way of defining the logic. To read more about lambda expressions, also check out our previous article.

3.2. Using Stream

The Stream API is another addition to Java 8 which has largely simplified working with collections:

public > V maxUsingStreamAndLambda(Map map) < Optional maxEntry = map.entrySet() .stream() .max((Entry e1, Entry e2) -> e1.getValue() .compareTo(e2.getValue()) ); return maxEntry.get().getValue(); >

This API offers a lot of data processing queries like map-reduce transformations on collections. Here, we’ve used max() over a stream of Map Entry which is a special case of a reduction operation. More details about the Stream API are available here.

We’re also making use of the Optional API here which is a container object added in Java 8 that may or may not contain a non-null value. More details about Optional can be obtained here.

3.3. Using Stream with Method Reference

Lastly, let’s see how method references can further simplify our use of lambda expressions:

public > V maxUsingStreamAndMethodReference(Map map) < Optional maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Map.Entry::getValue)); return maxEntry.get() .getValue(); >

In cases where lambda expressions are merely calling an existing method, a method reference allows us to do this using the method name directly. For more details about method references have a look at this previous article.

4. Conclusion

In this article, we’ve seen multiple ways of finding the highest value in a Java Map, some of which were using features added as part of Java 8.

As always, the code for the examples is 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:

Источник

Оцените статью