Search code examples
springlistspring-bootspring-mvcthymeleaf

Filter objects in List<Object>


How can I filter Objects in List with select? I have a City model. The service returns the List with all cities. Next, I would like to select the county with the first drop-down, and then, with the second drop-down, I only want to see the cities that are in this county. Thank you for help me.

Controller:

@GetMapping("/")
public String getCityPage(Model model){

    TreeSet<City> cityList=cityService.getAllTown().stream()
            .collect(Collectors.toCollection(
                    () -> new TreeSet<City>((p1, p2) -> p1.getCountry().compareTo(p2.getCountry()))));



    model.addAttribute("cityList",cityList);


    return "index";

}

html

<body>

<h4>Select Country</h4>
<select>
    <option th:if="${not #lists.isEmpty(cityList)}" th:each="city : ${cityList}" th:text="${city.country}" th:value="${city.country}"></option>
</select>
<h4>Select City</h4>
<select></select>
</body>

Service

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    CityRepository cityRepository;

    @Override
    public City createTown(City city) {
        return cityRepository.save(city);
    }

    @Override
    public List<City> getAllTown() {
        return cityRepository.findAll();
    }

    @Override
    public City getCityById(Long id) {
        return cityRepository.findById(id).get();
    }

    @Override
    public List<City> getAllTownsInCountry(String country) {
        return getAllTown().stream().filter(t->t.getCountry().equals(country)).collect(Collectors.toList());
    }


}

Model

@Getter
@Setter
@NoArgsConstructor
@Entity
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotNull
    private String country;
    @NotNull
    private String townname;
    @NotNull
    private Double area;

    public City(@NotNull String country, @NotNull String townname, @NotNull Double area) {
        this.country = country;
        this.townname = townname;
        this.area = area;
    }
}

Solution

  • You've two choices here, of which I consider the second to be much more clean:

    1. Send all your cities from all countries to the client and store them somewhere (hidden inputs, hidden table, wherever). Add an onchange event to the country select, and using javascript and depending on the country selected, load in the city select the correct cities, picking them up from wherever you stored them.

    2. Add an onchange event to the country select. On the javascript function called, make an AJAX call to the controller (since you are using Spring: you will need a @RestController and not a @Controller to handle the request, since you are not returning a view), get the cities for that country and load them on the cities select.