【问题标题】:Is there a way to compare two Strings with each other using java streams?有没有办法使用java流来比较两个字符串?
【发布时间】:2019-08-22 11:45:55
【问题描述】:

此方法比较两个字符串。其中一个来自一个对象。如果字符串匹配,则对象返回 id。


    private static Long getDefaultKag(Long mandandId) {
        List<MandantKagAccountEntity> mandantKagAccountEntities = new MandantKagAccountManager().findAllKags(mandandId);
        for (MandantKagAccountEntity mandantKagAccountEntity : mandantKagAccountEntities) {
            if (mandantKagAccountEntity.getKagText().equals("Default_kag")) {
                return mandantKagAccountEntity.getMandantKagId();
            }
        }
        return null;
    }


有没有办法用流解决这个问题?我的方法,但我不能再进一步了。

    private static long getDefaultKag(Long mandandId) {
        return new MandantKagAccountManager().findAllKags(mandandId).stream()
                .filter(m -> m.getKagText().equals("Default_Kag"))
                ...
                ...
                ...
    }

你知道如何解决这个问题吗?我还想知道这两种变体中哪一种对大量数据更有效。

【问题讨论】:

    标签: java list java-8 java-stream


    【解决方案1】:

    替换

    ...
    ...
    ...
    

    .map(MandantKagAccountEntity::getMandantKagId)
    .findFirst()
    .orElse(null);
    

    【讨论】:

    • @Thilo 您可能希望返回Optional&lt;Long&gt;,或OptionalLong 而不是Long
    • 是的,也许,我知道 Optional 在填充时不能再为零了,对吧?你能告诉我如果我使用 Optional 的好处以及之后我如何使用它吗?正常吗?
    • @Thilo 这是一个很好的话题stackoverflow.com/questions/23454952/uses-for-optional
    【解决方案2】:

    我认为它可以解决问题

          private static long getDefaultKag(Long mandandId) {
                    MandantKagAccountManager mandantKagAccountManager=new MandantKagAccountManager().findAllKags(mandandId).stream()
                            .filter(m -> m.getKagText().equals("Default_Kag")).findFirst()
                            .orElse(null);
                  if(mandantKagAccountManager!=null)
                        return mandantKagAccountManager.getMandantKagId()
                   return null;
    }
    

    【讨论】:

    • 因为MandantKagAccountManager.getMandantKagId() 和总体思路而被否决
    • 你可以将可选项映射到MandantKagAccountEntity::getMandantKagId 并去掉 if
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2020-05-06
    • 2019-04-03
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多