如何从 MAP 中获取 MATCH 值

How to get the MATCH value from MAP

我正在尝试弄清楚如何获取匹配值并将其存储在字符串变量中,这是我所做的:

出于示例目的,我创建了以下内容:

        Map<Attachment, String> mapattach = new HashMap<Attachment, String>();  
        Attachment a1 = new Attachment();
        a1.setId("one1");
        a1.setName("one");
        a1.setUrl("http://1.com");
    
        Attachment a2 = new Attachment();
        a2.setId("two2");
        a2.setName("two");
        a2.setUrl("http://2.com");
    
        Attachment a3 = new Attachment();
        a3.setId("three3");
        a3.setName("three");
        a3.setUrl("http://3.com");
    
        mapattach.put(a1, "one1");
        mapattach.put(a2, "two22");
        mapattach.put(a3, "three33");

        //java stream
        //it will match only one item and it returns
        String matchFound = mapattach.entrySet().stream()
            .filter( f -> recordIds.contains(f.getKey().getId()))
            .findFirst().toString();

以上代码returns一条记录的字符串:

结果:

 Optional[class Attachment {
     name: one
     id: one1
     mimeType: null
     url: http://1.com
     referenceId: null }=one1]

但我想要的只是url我该怎么办?

您快到了,这应该可以解决问题:

    Optional<String> optionalUrl = mapattach.entrySet().stream()
            .filter(f -> recordIds.contains(f.getKey().getId()))
            .findFirst()
            .map(attachmentStringEntry -> attachmentStringEntry.getKey().getUrl());
    
    urlMatchFound = optionalUrl.get(); // remember that it might not be present.