Java Map에서의 최대값과 관련된 키 검색
맵의 최대값과 관련된 키를 얻는 가장 쉬운 방법은 무엇입니까?
Collections.max(someMap)는 최대값에 대응하는 키를 원할 때 최대 키를 반환할 것이라고 생각합니다.
기본적으로 맵의 엔트리 세트에 대해 "현재 알려진 최대값"과 연관된 키를 모두 기억하면서 반복해야 합니다(또는 둘 다 포함된 엔트리만 기억합니다).
예를 들어 다음과 같습니다.
Map.Entry<Foo, Bar> maxEntry = null;
for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}
완전성을 위해 Java-8을 사용하는 방법을 소개합니다.
countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
또는
Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
또는
Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
Java-8을 사용한 심플한 1개의 라이너
Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
이 코드는 최대값을 가진 모든 키를 인쇄합니다.
public class NewClass4 {
public static void main(String[] args)
{
HashMap<Integer,Integer>map=new HashMap<Integer, Integer>();
map.put(1, 50);
map.put(2, 60);
map.put(3, 30);
map.put(4, 60);
map.put(5, 60);
int maxValueInMap=(Collections.max(map.values())); // This will return max value in the HashMap
for (Entry<Integer, Integer> entry : map.entrySet()) { // Iterate through HashMap
if (entry.getValue()==maxValueInMap) {
System.out.println(entry.getKey()); // Print the key with max value
}
}
}
}
적절한 루프를 정의함으로써 (명시적인 추가 루프를 사용하지 않고) 직접 실행하는 방법을 다음에 나타냅니다.Comparator
:
int keyOfMaxValue = Collections.max(
yourMap.entrySet(),
new Comparator<Entry<Double,Integer>>(){
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue() > o2.getValue()? 1:-1;
}
}).getKey();
1. 스트림 사용
public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue())
);
return maxEntry.get().getKey();
}
2. 람다 식과 함께 Collections.max() 사용
public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
.compareTo(e2.getValue()));
return maxEntry.getKey();
}
3. 메서드 레퍼런스를 사용한 스트림 사용
public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
Optional<Entry<K, V>> maxEntry = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue());
return maxEntry.get()
.getKey();
}
4. Collections.max() 사용방법
public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return e1.getValue()
.compareTo(e2.getValue());
}
});
return maxEntry.getKey();
}
5. 단순 반복 사용
public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
Map.Entry<K, V> maxEntry = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (maxEntry == null || entry.getValue()
.compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
return maxEntry.getKey();
}
맵이 비어 있는 경우 최대값이 없을 수 있으므로 Optional을 반환하는 응답:map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
다음 두 가지 방법이 있습니다.이 방법을 사용하여 최대값의 키를 가져옵니다.
public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){
Entry<String, Integer> maxEntry = null;
Integer max = Collections.max(map.values());
for(Entry<String, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
if(null != value && max == value) {
maxEntry = entry;
}
}
return maxEntry;
}
예를 들어 다음 방법을 사용하여 최대값으로 엔트리를 가져옵니다.
Map.Entry<String, Integer> maxEntry = getMaxEntry(map);
Java 8을 사용하면 최대값을 포함하는 개체를 가져올 수 있습니다.
Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("maxEntry = " + maxEntry);
이해하기 쉽다.아래 코드에서 maxKey는 최대값을 유지하는 키입니다.
int maxKey = 0;
int maxValue = 0;
for(int i : birds.keySet())
{
if(birds.get(i) > maxValue)
{
maxKey = i;
maxValue = birds.get(i);
}
}
Java 8을 통해 최대값으로 모든 키를 얻을 수 있습니다.
Integer max = PROVIDED_MAP.entrySet()
.stream()
.max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
.get()
.getValue();
List listOfMax = PROVIDED_MAP.entrySet()
.stream()
.filter(entry -> entry.getValue() == max)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(listOfMax);
또한 다음을 사용하여 병렬화할 수 있습니다.parallelStream()
대신stream()
소정의 지도
HashMap abc = 새로운 HashMap <> ( ) 。
최대값을 가진 모든 맵엔트리를 가져옵니다.
필터에서 다음 방법 중 하나를 사용하여 최소값 또는 최대값 세트에 대한 각 맵엔트리를 취득할 수 있습니다.
Collections.max(abc.values())
Collections.min(abc.values())
Collections.max(abc.keys())
Collections.max(abc.keys())
abc.entrySet().stream().filter(entry -> entry.getValue() == Collections.max(abc.values()))
필터 맵의 키만 취득하는 경우
abc.entrySet()
.stream()
.filter(entry -> entry.getValue() == Collections.max(abc.values()))
.map(Map.Entry::getKey);
필터링된 맵의 값을 가져오려면
abc.entrySet()
.stream()
.filter(entry -> entry.getValue() == Collections.max(abc.values()))
.map(Map.Entry::getvalue)
목록에 있는 모든 키를 가져오려면 다음 절차를 수행합니다.
abc.entrySet()
.stream()
.filter(entry -> entry.getValue() == Collections.max(abc.values()))
.map(Map.Entry::getKey)
.collect(Collectors.toList())
리스트내의 모든 값을 취득하는 경우는, 다음과 같이 합니다.
abc.entrySet()
.stream()
.filter(entry -> entry.getValue() == Collections.max(abc.values()))
.map(Map.Entry::getvalue)
.collect(Collectors.toList())
이 해결방법은 괜찮습니까?
int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count + 1 : 0);
}
Integer max = Collections.max(map.keySet());
System.out.println(max);
System.out.println(map);
int maxValue = 0;
int mKey = 0;
for(Integer key: map.keySet()){
if(map.get(key) > maxValue){
maxValue = map.get(key);
mKey = key;
}
}
System.out.println("Max Value " + maxValue + " is associated with " + mKey + " key");
맵의 Majority Element/max 요소:
public class Main {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
// or in this way
System.out.println(".............");
Integer maxAppearedElement = map.entrySet()
.parallelStream()
.max(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.get();
System.out.println(maxAppearedElement);
}
}
프로젝트에서는 Jon's and Pathah의 솔루션을 약간 수정한 버전을 사용했습니다.같은 값을 가진 엔트리가 여러 개일 경우 마지막으로 발견된 엔트리가 반환됩니다.
public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map) {
Entry<String, Integer> maxEntry = null;
Integer max = Collections.max(map.values());
for(Entry<String, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
if(null != value && max == value) {
maxEntry = entry;
}
}
return maxEntry;
}
그러면 최대값의 키가 반환됩니다.Map<Integer, Integer>
public Set<Integer> getMaxKeys(Map<Integer, Integer> map) {
if (map.isEmpty()) {
return Collections.emptySet();
}
return map
.entrySet()
.stream()
.collect(
groupingBy(
Map.Entry::getValue, TreeMap::new, mapping(Map.Entry::getKey, toSet())
)
)
.lastEntry()
.getValue();
}
그렇게 해도 좋다
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
hm.put(1,10);
hm.put(2,45);
hm.put(3,100);
Iterator<Integer> it = hm.keySet().iterator();
Integer fk = it.next();
Integer max = hm.get(fk);
while(it.hasNext()) {
Integer k = it.next();
Integer val = hm.get(k);
if (val > max){
max = val;
fk=k;
}
}
System.out.println("Max Value "+max+" is associated with "+fk+" key");
가장 간단한 방법은 다음과 같습니다.
Collections.max(hmap.values());
언급URL : https://stackoverflow.com/questions/5911174/finding-key-associated-with-max-value-in-a-java-map
'it-source' 카테고리의 다른 글
참조 - 이 기호는 PHP에서 무엇을 의미합니까? (0) | 2022.12.09 |
---|---|
python 스크립트의 실행을 프로그래밍 방식으로 중지하시겠습니까? (0) | 2022.12.09 |
스위치 대/소문자 문 오류: 대/소문자 표현은 상수 표현이어야 합니다. (0) | 2022.12.09 |
try/catch vs through 예외 (0) | 2022.12.09 |
LIMIT는 MariaDB에서 동작하지 않는다 - 많은 시도를 했다 (0) | 2022.12.09 |