0

I have a Vector of location, which has country, state and city all as Strings. I want to display the data as: USA | texas | austin, dallas, houston... USA | californa | la, san francisco ...

What I have:

   <c:forEach items="${locations}" var="location" >
       <h4><c:out value="${location.country.name}"/></h4>
       <h4><c:out value="${location.state.name}"/></h4>
       <h4><c:out value="${location.city.name}"/></h4>
   </c:forEach>

What is the best way to skip country and state name if they are same as the last value. I am sure I can use local variables for currentCountry and currentState to not show duplicate values. I just want to know the best practice.

Thanks,

1 Answer 1

3

The best and the easiest way to do that is to add you list (in this of type vector) to a set, a HashSet for instance. You can add the list of location.city.name to the set, with a loop, duplicates will be removed automatically from the set, then you display your set of cities.

 Set<String> setOfCities = new HashSet();
   for(int i = 0; i< setOfCities.size(); i++){
       setOfCities.add(location.city.name);
   }

Or if you want to add directly the list of location, which are not of type String, you have to implement the Comparator interface to be able to compare your list of locations and remove duplicate. To override the equals() method, you can look this post: https://stackoverflow.com/a/5741080/3010827

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.