Search code examples
javalambdajava-streamcollectors

Succinct way to express a block of code using lambda and streams


Hi I have a block of code that converts a list of one kind of window object to another kind and stuffs it in a map, keyed by the id. There could be many instances of the objects with same id but with different name and attrs. What I'm doing is taking a list [W1(1,2,3), W1(2,3,4), W2(1,3,4)...] and converting it to Map [ key W1 , values (1,2,3), (2,3,4) key W2, .... ]

Here is the code snippet...

    List<LinWin> list = winDao.get.....

    Map<Long, List<MacWin>> res = new HashMap<>();
    for (LinWin mw : list) {

        List<MacWin> l2 = res.get(mw.getId());
        if (l2 == null) {
            l2 = new ArrayList<>();
            res.put(mw.getId(), l2);
        }
        l2.add(new MacWin(mw.getName(), mw.getVendor(), mw.isFixed()));
    }

return res

I was wondering if I could use streams and lambdas to collapse this.

list.stream().collect(Collectors.toMap(.....


Solution

  • This can be simplified indeed if you for example would have a method that would transform from LinWin to MacWin (either make it static or create a constructor for MacWin that would accept a LinWin as input). I'll generate a static method here:

    private static MacWin of(LinWin lw){
        return new MacWin(mw.getName(), mw.getVendor(), mw.isFixed());
    }
    

    And later usage would be (I don't use streams here, since in this case doing things without streams, looks easier for me):

    Map<Long, List<MacWin>> res = new HashMap<>();
    mw.forEach(x -> res.computeIfAbsent(mw.getId(), y -> new ArrayList<>()).add(of(x)));