首页 > 解决方案 > 如何从 MAP 获取 MATCH 值

问题描述

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

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

        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();

上面的代码返回一条记录的字符串:

结果:

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

但我想要的是url我该怎么做?

标签: streamjava-stream

解决方案


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

    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.

推荐阅读