Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 迭代并比较同一映射中的值,以找到最大值,并从同一映射中删除其他值_Java_Map - Fatal编程技术网

Java 迭代并比较同一映射中的值,以找到最大值,并从同一映射中删除其他值

Java 迭代并比较同一映射中的值,以找到最大值,并从同一映射中删除其他值,java,map,Java,Map,我有 我应该尝试迭代和比较这个映射中的值,并且我希望映射元素的值最大,并且映射应该只包含那个元素 我将使用包装器类: myMap.put(k1,5); myMap.put(k2,20); myMap.put(k3,10); myMap.put(k4,15); 公共类MyMapWrapper{ 私人V最大值; 私有K-maxKey; 私有最终映射=新HashMap(); 私人最终比较公司; 公共MyMapWrapper(){ 这个(新的比较器(){ 公共整数比较(v1,v2){ 返回(v

我有


我应该尝试迭代和比较这个映射中的值,并且我希望映射元素的值最大,并且映射应该只包含那个元素

我将使用包装器类:

 myMap.put(k1,5);
 myMap.put(k2,20);
 myMap.put(k3,10);
 myMap.put(k4,15);
公共类MyMapWrapper{
私人V最大值;
私有K-maxKey;
私有最终映射=新HashMap();
私人最终比较公司;
公共MyMapWrapper(){
这个(新的比较器(){
公共整数比较(v1,v2){
返回(v1==null)?((v2==null)?0:-1):v1.compareTo(v2);
}
});
}
公共MyMapWrapper(比较器组件){
if(comp==null){
//比较器不应为空
抛出新的IllegalArgumentException(“Comparator不能为null!”);
}
this.comp=comp;
}
公共V getMaximum(){
返回此值。最大值;
}
公共K getMaximumKey(){
返回此.maxKey;
}
公共整数输入(K键,V值){
如果(值==null){
//您不需要空的可比较项,可以抛出异常或忽略
抛出新的IllegalArgumentException(“不允许空值!”);
}
如果(this.max==null | | this.comp.compareTo(this.max,value)>0){
这是最大值;
this.maxKey=key;
}
返回此.map.put(键,值);
}
公共整数删除(K键){
V back=this.map.remove(键);
如果(此最大值等于(后)){
K newKey=null;
V newMax=null;
//在地图上搜索新的最大值
对于(Map.Entry-ent:this.Map.entrySet()){
如果(此.comp.compareTo(ent.getValue(),newMax)>0){
newMax=ent.getValue();
newKey=ent.getKey();
}
}
this.max=newMax;
this.maxKey=newKey;
}
返回;
}
公共V get(K键){
返回此.map.get(键);
}
}
如果需要其他特定方法,您可以这样做,但这只需要使用一个“映射”:

public class MyMapWrapper<K, V extends Comparable> {

    private V maximum;
    private K maxKey;
    private final Map<K, V> map = new HashMap<>();
    private final Comparator<V> comp;

    public MyMapWrapper() {
        this(new Comparator<V>() {

            public int compareTo(V v1, V v2) {
                return (v1 == null) ? ((v2 == null) ? 0 : -1) : v1.compareTo(v2);
            }

        });
    }

    public MyMapWrapper(Comparator<V> comp) {
        if (comp == null) {
            //Comparator should not be null
            throw new IllegalArgumentException("Comparator cannot be null!");
        }
        this.comp = comp;
    }

    public V getMaximum() {
        return this.maximum;
    }

    public K getMaximumKey() {
        return this.maxKey;
    }

    public int put(K key, V value) {
        if (value == null) {
            //You don't want null comparables, can either throw an exception or ignore
            throw new IllegalArgumentException("No null values allowed!");
        }
        if (this.maximum == null || this.comp.compareTo(this.maximum, value) > 0) {
            this.maximum = value;
            this.maxKey = key;
        }
        return this.map.put(key, value);
    }

    public int remove(K key) {
        V back = this.map.remove(key);
        if (this.maximum.equals(back)) {
            K newKey = null;
            V newMax = null;
            //search map for new maximum
            for (Map.Entry<K, V> ent : this.map.entrySet()) {
                if (this.comp.compareTo(ent.getValue(), newMax) > 0) {
                    newMax = ent.getValue();
                    newKey = ent.getKey();
                }
            }
            this.maximum = newMax;
            this.maxKey = newKey;
        }
        return back;
    }

    public V get(K key) {
        return this.map.get(key);
    }

}
MyMapWrapper示例=新建MyMapWrapper();
示例.put(“test1”,14);
示例.put(“test2”,3450);
例如,put(“test4”,-142);
System.out.println(String.format(“最大键:%s,最大值:%d”,example.getMaximumKey(),example.getMaximum());
//最大键:“test2”,最大值:3450
这还允许对值使用自定义比较器:

MyMapWrapper<String, Integer> example = new MyMapWrapper<>();
example.put("test1", 14);
example.put("test2", 3450);
example.put("test4", -142);
System.out.println(String.format("Max key: %s, Max value: %d", example.getMaximumKey(), example.getMaximum());
//Max key: "test2", Max value: 3450
MyMapWrapper示例=新的MyMapWrapper(新的Comparator(){
公共整数比较(整数v1,整数v2){
返回(v2==null)?((v1==null)?0:-1):v2.比较(v1);
}
});
示例.put(“test1”,14);
示例.put(“test2”,3450);
例如,put(“test4”,-142);
System.out.println(String.format(“最大键:%s,最大值:%d”,example.getMaximumKey(),example.getMaximum());
//最大键:“test4”,最大值:-142

简单的解决方案是使用并发hashmap。试试这个

MyMapWrapper<String, Integer> example = new MyMapWrapper<>(new Comparator<Integer>() {

    public int compareTo(Integer v1, Integer v2) {
        return (v2 == null) ? ((v1 == null) ? 0 : -1) : v2.compareTo(v1);
    }

});
example.put("test1", 14);
example.put("test2", 3450);
example.put("test4", -142);
System.out.println(String.format("Max key: %s, Max value: %d", example.getMaximumKey(), example.getMaximum());
//Max key: "test4", Max value: -142
import java.util.HashMap;
导入java.util.Map;
导入java.util.concurrent.ConcurrentHashMap;
公务舱{
公共静态void main(字符串[]args){
Map myMap=newhashmap();
myMap.put(1,5);
myMap.put(2,20);
myMap.put(3,10);
myMap.put(4,15);
myMap.put(5,20);
System.out.println(myMap);
Map concurrentMap=新的ConcurrentHashMap(myMap);
整数maxKey=concurrentMap.keySet().iterator().next();
整数max=myMap.get(maxKey);
for(整数键:concurrentMap.keySet()){
整数值=concurrentMap.get(键);
如果(最大值>当前值){
concurrentMap.remove(键);
}否则如果(最大值<当前值){
concurrentMap.remove(maxKey);
max=concurrentMap.get(键);
maxKey=key;
}
}
System.out.println(concurrentMap);
}
}

如果您只想获取
地图中的max
条目
,请使用
Collections.max
和您定义的
比较器

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Largest {

    public static void main(String[] args) {
        Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
        myMap.put(1, 5);
        myMap.put(2, 20);
        myMap.put(3, 10);
        myMap.put(4, 15);
        myMap.put(5, 20);

        System.out.println(myMap);

        Map<Integer, Integer> concurrentMap = new ConcurrentHashMap<Integer, Integer>(myMap);

        Integer maxKey = concurrentMap.keySet().iterator().next();
        Integer max = myMap.get(maxKey);

        for(Integer key : concurrentMap.keySet()){
            Integer currValue = concurrentMap.get(key);
            if(max > currValue){
                concurrentMap.remove(key);
            } else if(max < currValue) {
                concurrentMap.remove(maxKey);
                max = concurrentMap.get(key);
                maxKey = key;
            }
        }

        System.out.println(concurrentMap);
    }

}

如果您有java 8,您可以这样做:

代码

myMap.clear();
myMap.put(maxEntry.key(), maxEntry.value());

在映射中查找最大值很简单,但我不知道“从同一映射中删除其他元素”和“映射应仅包含该元素”是什么意思。如果您只需要映射中的单个元素,为什么要使用映射?为什么不只存储到常规变量,而只在新值较大时重置该变量?“map应该只包含那个元素”和“remove other from same map”意味着当我比较两个元素时,例如element1(value=5)和element2(value=20),在本例中具有较小值的元素element1(value=5)应该从map中删除,这样我就可以将element2与map中的下一个元素,即element3进行比较(value=10),依此类推,这样我将在映射中只保留值最大的元素。@Magnus..我们不能总是保证一个条目。假设两个键具有相同的值,这两个键在映射中都是最大的,那么生成的映射将有两个条目..只是一个想法:)为什么不使用Collections.max()在原始地图上?@bcorso好的,这实际上是一个最大值的“缓存”,因此我认为它会更有效。在定义实现时也提供了更大的灵活性。
Map<Key, Integer> myMap= new HashMap<Key,Integer>();
myMap.put(k1,5);
myMap.put(k2,20);
myMap.put(k3,10);
myMap.put(k4,15);

Entry<Key, Integer> maxEntry = Collections.max(myMap.entrySet(), 
    new Comparator<Entry<Key, Integer>>(){
        @Override public int compare(Entry<Key, Integer> e1, Entry<Key, Integer> e2) {
            return e1.getValue().compareTo(e2.getValue());
        }
    });

// outputs k2=20
System.out.print(maxEntry);
myMap.clear();
myMap.put(maxEntry.key(), maxEntry.value());
public class MapFiltering {

    public static void main(String[] args) {
        Random rnd = new Random();
        Map<String, Integer> myMap = new HashMap<>();
        int i = 1;
        for (int j = 0; j < 10; j++) {
            myMap.put("k" + j, rnd.nextInt(100));
        }
        System.out.println("BEFORE");
        printMap(myMap);
        filterMap(myMap);
        System.out.println("AFTER");
        printMap(myMap);
    }

    private static void printMap(Map<String, Integer> map) {
        map.entrySet().stream().forEach((e) -> {
            System.out.println("K=" + e.getKey() + " V=" + e.getValue());
        });
    }

    private static void filterMap(Map<String, Integer> map) {
        Map.Entry<String, Integer> get
                = map.entrySet()
                .stream()
                .max((Comparator<? super Map.Entry<String, Integer>>) new Comparator<Map.Entry<String, Integer>>() {

                    @Override
                    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                        return o1.getValue().compareTo(o2.getValue());
                    }
                }).get();
        map.clear();
        map.put(get.getKey(), get.getValue());
    }
}
BEFORE
K=k0 V=66
K=k1 V=5
K=k2 V=34
K=k3 V=54
K=k4 V=52
K=k5 V=69
K=k6 V=34
K=k7 V=62
K=k8 V=73
K=k9 V=28
AFTER
K=k8 V=73