Immutable map serializer: replace foreach loops with while loops