diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java b/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java index 4fa18da91..9566b3bc6 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetTypeFormatter.java @@ -1,18 +1,3 @@ -/* - * Copyright 2012-2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.springframework.samples.petclinic.owner; import org.springframework.beans.factory.annotation.Autowired; @@ -22,16 +7,10 @@ import org.springframework.stereotype.Component; import java.text.ParseException; import java.util.Collection; import java.util.Locale; +import java.util.Optional; /** - * Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting - * from Spring 3.0, Formatters have come as an improvement in comparison to legacy - * PropertyEditors. See the following links for more details: - The Spring ref doc: - * https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#format - * - * @author Mark Fisher - * @author Juergen Hoeller - * @author Michael Isvy + * Formatter to parse and print 'PetType' elements. */ @Component public class PetTypeFormatter implements Formatter { @@ -50,13 +29,20 @@ public class PetTypeFormatter implements Formatter { @Override public PetType parse(String text, Locale locale) throws ParseException { - Collection findPetTypes = this.owners.findPetTypes(); - for (PetType type : findPetTypes) { - if (type.getName().equals(text)) { - return type; - } - } - throw new ParseException("type not found: " + text, 0); + Optional petType = findPetTypeByName(text); + return petType.orElseThrow(() -> new ParseException("PetType not found: " + text, 0)); } + /** + * Helper method to find a PetType by its name. + * @param name the name of the pet type to search for + * @return an Optional containing the PetType if found, or an empty Optional + */ + private Optional findPetTypeByName(String name) { + return this.owners.findPetTypes() + .stream() + .filter(petType -> petType.getName().equalsIgnoreCase(name)) + .findFirst(); + } } +