Convert a complex method into Lambda Expression

184 Views Asked by At

i want to write my code below, with new stuff. I want to use Java8 stream and functional programming.

private static void algoritmoSolC(List<Storage> freeSpaces, Double dimPacket, Double nPackets,
            int storageIndex) {
        if (nPackets == 0)
            return;

        List<Storage> list = new ArrayList(freeSpaces) {
            public Object get(int index) {
                if (index < 0) {
                    index = Math.abs(index);
                } else if (index >= size()) {
                    index = index % size();
                }
                return super.get(index);
            }
        };
        for (int i = 0; i < nPackets; i++) {
            Storage storage = list.get(storageIndex);
            if (storage.getFreeSpace() > dimPacket) {
                storage.setFreeSpace(storage.getFreeSpace() - dimPacket);
                ++storageIndex;
            } else {
                ++storageIndex;
                ++nPackets;
            }
        }
    }

I think if I convert code in functional programming, I spent less time for result. Can anyone help me to convert this snippet of code? Thanks in advance

1

There are 1 best solutions below

0
On BEST ANSWER

Didnt really tested it but it could go about this:

IntStream
 .range(storageIndex,Integer.MAX_VALUE)
 .mapToObj(i-> freeSpaces.get(Math.abs(i) % freeSpaces.size()))
 .filter(storage -> storage.getFreeSpace() > dimPacket)
 .limit(nPackets)
 .forEach(storage.setFreeSpace(storage.getFreeSpace() - dimPacket))

Looking at this it is really surprisingly more elegant thant your code :-)