2

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Hubi
  • 440
  • 1
  • 11
  • 25

2 Answers2

5

Replace

...
...
...

with

.map(MandantKagAccountEntity::getMandantKagId)
.findFirst()
.orElse(null);
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • @Thilo you may want to return an `Optional`, or `OptionalLong` instead of `Long` – Andrew Tobilko Aug 22 '19 at 12:05
  • yeah maybe, i know that Optional, when filled, can not be zero anymore, right?. could you tell me the advantages if i would use Optional and how i can work with it afterwards? like normal? – Hubi Aug 22 '19 at 12:54
  • @Thilo here's a good topic https://stackoverflow.com/questions/23454952/uses-for-optional – Andrew Tobilko Aug 22 '19 at 12:56
0

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;
}
yogev levi
  • 369
  • 1
  • 4
  • 21