Get minvalue of a Map(Key,Double)
You can use the standard Collections#min()
for this.
Map<String, Double> map = new HashMap<String, Double>();
map.put("1.1", 1.1);
map.put("0.1", 0.1);
map.put("2.1", 2.1);
Double min = Collections.min(map.values());
System.out.println(min); // 0.1
Update: since you need the key as well, well, I don't see ways in Collections
or Google Collections2
API since a Map
is not a Collection
. The Maps#filterEntries()
is also not really useful, since you only know the actual result at end of iteration.
Most straightforward solution would then be this:
Entry<String, Double> min = null;
for (Entry<String, Double> entry : map.entrySet()) {
if (min == null || min.getValue() > entry.getValue()) {
min = entry;
}
}
System.out.println(min.getKey()); // 0.1
(nullcheck on min
left aside)
How can I find the minimum value in a map?
You have a few options. The "best" way to do this is with a functor, this is guaranteed to be the fastest to call:
typedef std::pair<std::string, int> MyPairType;
struct CompareSecond
{
bool operator()(const MyPairType& left, const MyPairType& right) const
{
return left.second < right.second;
}
};
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min
= *min_element(mymap.begin(), mymap.end(), CompareSecond());
return min.second;
}
(You can also nest the CompareSecond
class inside MyClass
.
With the code you have now, you can easily modify it to work, however. Just make the function static
and use the correct syntax:
static bool
MyClass::compare(std::pair<std::string, int> i, std::pair<std::string, int> j)
{
return i.second < j.second;
}
int MyClass::getMin(std::map<std::string, int> mymap)
{
std::pair<std::string, int> min = *min_element(mymap.begin(), mymap.end(),
&MyClass::compare);
return min.second;
}
Find minimum value in a map java
Simple java8 solution for map Map<Object,Integer> map = new HashMap<>();
map.values().stream().min(Integer::compare).get();
Edit
As @Andreas pointed out, there was request for using comparator, so this is solution for Java 8 which finds smallest value
public static <K, V> V min8(Map<K, V> map, Comparator<V> comp) {
return map.values().stream().min(comp).get();
}
and this is solution for Java 7 for finding entry with smallest value
public static <K, V> Entry<K, V> min(Map<K, V> map, Comparator<V> comp) {
Iterator<Entry<K, V>> entries = map.entrySet().iterator();
if (!entries.hasNext()) {
return null;
}
Entry<K, V> min;
for (min = entries.next(); entries.hasNext();) {
Entry<K, V> value = entries.next();
if (comp.compare(value.getValue(), min.getValue()) < 0) {
min = value;
}
}
return min;
}
my initial solution was very close to @Andreas, so i decide to change and use for loop with itterator.
Find the Min of Max values in a MapString, ListInteger without relying on for loops
You can use the methods Collections.min and Collections.max
HashMap<String, List<Integer>> myMap = new HashMap<>();
Integer min = Collections.min(myMap.values().stream().map(Collections::max).collect(Collectors.toList()));
Finding first, second, third minimum in hash map
Not quite understood second part about repeat, anyway it may help:
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(1,10);
map.put(2,100);
map.put(3,20);
map.put(4,990);
Map.Entry<Integer, Integer> integerIntegerEntry = map.entrySet()
.stream().min(Comparator.comparing(Map.Entry::getKey))
.orElseThrow(() ->new RuntimeException("Oops!"));
System.out.println("min val is :" + integerIntegerEntry.getValue());
anotherMethod(integerIntegerEntry.getKey());
}
How to find the lowest value in a HashMap
In your loop, compare the value to the current smallest and remember the smallest:
Integer smallestValue = Integer.MAX_VALUE;
String smallestKey;
for (HashMap.Entry<String, Integer> entry : itemTime.entrySet()) {
if (entry.getValue() < smallestValue) {
smallestKey = entry.getKey();
smallestValue = entry.getValue();
}
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.pintln("Smallest is " + smallestKey + " with " + smallestValue);
Getting min value from a hashmap which stores a object as value
You can create a Comparator
that sorts based on area
and get the Entry
from Map
Comparator<Map.Entry<String, Country>> comp =
Comparator.comparing((Entry<String, Country> entry)->entry.getValue().getArea());
Using Collections.min
Collections.min(biggestCountries.entrySet(),comp);
Using stream
Entry<String, Country> entry = biggestCountries.entrySet()
.stream()
.min(comp)
.orElse(null);
If you want to get only the Country
, using stream
Country minCountry = biggestCountries.values()
.stream()
.min(Comparator.comparing(Country::getArea))
.orElse(null);
or using Collections.min
Country minCountry = Collections.min(biggestCountries.values(),
Comparator.comparing(Country::getArea));
Get key with minimum value
You can get the key and value using Object.entries
:
var arr = { lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49};
function lowestValueAndKey(obj) { var [lowestItems] = Object.entries(obj).sort(([ ,v1], [ ,v2]) => v1 - v2); return `Lowest value is ${lowestItems[1]}, with a key of ${lowestItems[0]}`;}
var lowest = lowestValueAndKey(arr);console.log(lowest);
Find minimum key in map with Java 8 stream
Do you really need Map.Entry.comparingByValue()
?
You can "implement" your (almost :)) own Comparator
:
.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )
Related Topics
Why Compile Error with Enable_If
How to Check for Inf (And | Or) Nan in a Double Variable
Why Is Operator""S Hidden in a Namespace
Catching Signals: Use a Member Function as Signal Handler
C++11 Random Number Distributions Are Not Consistent Across Platforms -- What Alternatives Are There
Get Device Path Based on Usb Vid:Pid in Linux
How to Perform Rgb->Yuv Conversion in C/C++
C++11 Struct Initialization Compilation Error
Warning: Narrowing Conversion C++11
C++: How to Check Type of Files Without Extension
Cudamalloc of a Structure and an Element of Same Structure
Using Crypto++ Static Library in a Qt Project
Getting Cannot Allocate Memory Error
How to Start Process on Linux Os in C, C++
Msvc Equivalent of _Attribute_ ((Warn_Unused_Result))
Gdb Nostop Sigsegv on a Specific Thread
Template Metaprogramming: (Trait For) Dissecting a Specified Template into Types T<T2,T3 N,T4, ...>