简体   繁体   中英

Is there a way to compare two Strings with each other using java streams?

This method compares two strings. One of them comes from an object. If the strings match, the id is returned by the object.


    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;
    }


Is there any way to solve this with streams? My approach, but I can't get any further.

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

Do you have any idea how to solve this? I would also like to know which of the two variants is more efficient for large amounts of data.

Replace

...
...
...

with

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

I think it will do the trick

      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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM