簡體   English   中英

根據密鑰從 HashMap 中獲取不同的值

[英]Get distinct value from HashMap based on key

我有一個 HasMap,鍵為字符串,值為字符串類型的列表。 在具有 String 類型 List 的值中,只有 2 個值存在。 現在我需要比較其他鍵值 w.r.t 所有鍵第一個和第二個值是否相同。 如果第一個或第二個不同,則需要該 hashmap 值。 請幫忙。

  HashMap<String,List<String>> =  new HashMap<>();
    // eg: ==> "John",["4","5"]
    
    // check for other keys if  any of 2 values is/are  different  then get that row.
     // suppose 2nd entry is ==> "Michael",["4","6"] , get that distinct value  
     //or "Michael",["5","4"]  ==> print both because value 1& value 2 not same as John. (order is changed). any 1 value can be null.
     // if unique do nothing.

這是打印條目的示例應用程序,其值與 John 的不同:

public class DifferentValues {
    public static void main(String[] args) {
        HashMap<String, List<String>> map =  new HashMap<>();
        map.put("John", Arrays.asList("4", "5"));
        map.put("Michael", Arrays.asList("5", "4"));

        List<String> baseValue = map.get("John");
        for (Map.Entry<String, List<String>> entry: map.entrySet()) {
            if (!"John".equals(entry.getKey()) && !equalLists(entry.getValue(), baseValue)) {
                System.out.println(entry.getKey() + " -> {" + String.join(", ", entry.getValue()) + "}");
            }
        }
    }

    private static boolean equalLists(List<String> a, List<String> b) {
        if (a.size() != b.size()) {
            return false;
        }
        Iterator<String> aIter = a.iterator();
        for (Iterator<String> bIter = b.iterator(); aIter.hasNext();) {
            if (!Objects.equals(aIter.next(), bIter.next())) {
                return false;
            }
        }
        return true;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM