簡體   English   中英

在地圖中返回密鑰 <String,List<Pair<Integer,String> &gt;&gt;

[英]Returning the Key in a Map<String,List<Pair<Integer,String>>>

我已經使用TreeMap <String,List <Pair <Integer,String >>>類型定義了一個集合,其中pair是我定義的一個類:

public class Pair<L,R> {
    private L l; 
    private R r; 
    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}

}

我想返回與包含給定String值的列表配對的字符串(TreeMap鍵)。 例如,我有一個字符串“ bob”存儲在列表中的一對中,並且我想返回與該“ bob”所在的對列表相關聯的Treemap的鍵(字符串)。我將如何去做呢?

我將創建謂詞,由內而外地工作。 希望您能遵循邏輯。 這將找到第一個具有“ Bob”的列表並獲取該密鑰。

Predicate<Pair<Integer, String>> pairHasBobPred = pair -> ((String) pair.getR()).equals("Bob");

Predicate<String> keyHasBobPred = key -> myTree.get(key).stream()
                                                    .anyMatch(pairHasBobPred::test);

String keyWithBob =  myTree.keySet().stream()
                                    .filter(keyHasBobPred::test)
                                    .findFirst()
                                    .get();

這本質上是反向查找。 您具有與值關聯的鍵的map ,並且想要找到關聯的值滿足某些條件的鍵。 請注意,在最壞的情況下,這將導致整個表查找非常昂貴,因為您最終可能會訪問映射中的每個條目。

對於初學者,我會做一些非常簡單的事情,如下所示。 我已經自由地修改了Pair類。 下面根據您的要求打印密鑰key2

public class ReverseLookup {
    static class Pair<L,R> {
        private L l;
        private R r;
        public Pair(L l, R r) {
            this.l = l;
            this.r = r;
        }
        public L getL() {return l;}
        public R getR() {return r;}
        public void setL(L l){this.l = l;}
        public void setR(R r){this.r = r;}

        public static <L, R> Pair<L, R> right(List<Pair<L, R>> pairs, R rVal) {
            for (Pair<L, R> pair : pairs) {
                if (rVal != null && rVal.equals(pair.getR()))
                    return pair;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        String lookFor = "bob";
        Map<String, List<Pair <Integer, String>>> listOfPairs = new TreeMap<>();
        listOfPairs.put(
            "key1", Arrays.asList(new Pair("2", "carol"), new Pair(4, "david"))
            );
        listOfPairs.put(
        "key2", Arrays.asList(new Pair("0", "alice"), new Pair(1, "bob"))
        );
        for (Map.Entry<String, List<Pair<Integer, String>>> entry : listOfPairs.entrySet()) {
            // entry is a mapping from string -> list of pairs Integer, String
            List<Pair<Integer, String>> pairs = entry.getValue();
            if (Pair.right(pairs, lookFor) != null) {
                System.out.println(entry.getKey());
            }
        }
    }
}

暫無
暫無

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

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