I'm looking for a way to create a collection, list, set, or map which contains the transformed elements of an original collection and reflects every modification in that collection.
For example if I have a List<Integer>
from a third party API and another API is expecting a List<String>
. I know I can transform the list like this:
List<Integer> intList = thirdPartyBean.getIntListProperty();
List<String> stringList = intList.stream().map(Integer::toString)
.collect(Collectors.toList());
secondBean.setStringListProperty(stringList);
The problem is, if anything is changed in one of the lists the other one will still reflect the previous state. Let's assume that intList
contains [1, 2, 3]
:
intList.add(4);
stringList.remove(0);
System.out.println(intList.toString()); // will print: [1, 2, 3, 4]
System.out.println(stringList.toString()); // will print: [2, 3]
// Expected result of both toString(): [2, 3, 4]
So I'm searching for something like List.sublist(from, to)
where the result is "backed" by the original list.
I'm thinking of implementing my own list wrapper which is used like this:
List<String> stringList = new MappedList<>(intList, Integer::toString, Integer::valueOf);
The second lambda is for inverting the conversion, to support calls like stringList.add(String)
.
But before I implement it myself I would like to know if I try to reinvent the wheel - maybe there is already a common solution for this problem?