diff --git a/src/main/java/org/springframework/hateoas/RepresentationModel.java b/src/main/java/org/springframework/hateoas/RepresentationModel.java index e207adbd..e7437980 100755 --- a/src/main/java/org/springframework/hateoas/RepresentationModel.java +++ b/src/main/java/org/springframework/hateoas/RepresentationModel.java @@ -21,6 +21,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -299,6 +300,25 @@ public class RepresentationModel> { return getLinks(relation.value()); } + /** + * Replaces the link(s) with the given {@link LinkRelation} with the mapper applied to each of the links. + * + * @param relation the {@link LinkRelation} to select the source link(s), must not be {@literal null}. + * @param mapper the {@link Function} to apply to the current link, must not be {@literal null}. + * @return will never be {@literal null}. + * @since 1.3 + */ + public T mapLink(LinkRelation relation, Function mapper) { + + getLinks(relation).forEach(it -> { + + links.remove(it); + links.add(mapper.apply(it)); + }); + + return (T) this; + } + /* * (non-Javadoc) * @see java.lang.Object#toString() diff --git a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java index aa074c96..d190b79c 100755 --- a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java @@ -194,4 +194,14 @@ class RepresentationModelUnitTest { model.addAllIf(false, () -> Links.of(Link.of("not-added", "bar"))); assertThat(model.hasLink("bar")).isFalse(); } + + @Test // #1457 + void replacesLink() { + + RepresentationModel model = new RepresentationModel<>(); + model.add(Link.of("/foo", IanaLinkRelations.SELF)); + model.mapLink(IanaLinkRelations.SELF, it -> Link.of("/bar")); + + assertThat(model.getRequiredLink(IanaLinkRelations.SELF).getHref()).isEqualTo("/bar"); + } }