[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now


How to modify a java list based on rules efficiently

Posted on 2014-12-15
Medium Priority
Last Modified: 2014-12-16
I have a list populated from a service. I want to modify the list( add or delete from list)  based on the locale of the webapp. Since there are bunch of rules I am looking for a efficient way to do that in a spring webapp. Any thoughts?
Question by:greenearth
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 36

Expert Comment

ID: 40501654
If the service returns a List and there are no other alternatives there, then pretty much your only solution would be to iterate through the entire list.

As for modifying the list this is fairly easy if you use a ListIterator. Some example code follows...

List<?> results = service.getList();         // Or however you get your list from the service

ListIterator<?> iter = results.listIterator();
while (iter.hasNext()) {
    ? originalItem = iter.next();

    if (  /* your rules logic can go here */ ) {
        // Either..
        iter.add(new ?);  // Where the new ? can be based off the originalItem somehow, or...
        iter.remove();     // If you need to delete this element, or...
        iter.set(new ?);   // If you want to replace the originalItem with a new ?

Open in new window

Replace the "?" with whatever type is in your list. Also, I know the above is fairly general, if you can give more detail about what you are trying to do, I could be more specific in my assistance.

Author Comment

ID: 40501773
This would be very generic and would get ugly when we have lot of if statements.

My usecase would be lets say if the List returns bunch of fruits then based on certain states  I would not display certain fruits or always append few fruits for certain states based on my selection from a dropdown. For example for florida I always want to add Oranges even if the service does or does not have Oranges in the List .  For Texas I always want to delete Grapes even if the List does or does not have Grapes in it.
My application is spring based webapp. Is there a way we would be able to do it configurable.
LVL 36

Accepted Solution

mccarl earned 2000 total points
ID: 40501793
Ok, well this is some more useful information, check out the below sample code...

private Map<String, Set<Fruit>> addFruits = ....      // You would populate this map somehow with the "state"
                                                      //   as the key and a Set of Fruits to add for that state, ie. {"florida"=<Oranges>,"ohio"=<Bananas, Lemons>}
private Map<String, Set<Fruit>> deleteFruits = ....   // You would populate this map somehow with the "state"
                                                      //   as the key and a Set of Fruits to delete for that state, ie. {"Texas"=<Grapes>}

// ...

public List<Fruit> processFruitsPerState(String state, List<Fruit> originalFruits) {
    Set<Fruit> fruitSet = new LinkedHashSet<Fruit>();         // Note you could also just use HashSet here if you don't need
                                                              //   to maintain the "ordering" of Fruits in the originalFruits list


    return new ArrayList<Fruit>(fruitSet);

Open in new window

Note: you would want to add null checking, error checking, etc to the above, but I just wanted to keep it clean and understandable.
Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf


Author Comment

ID: 40502849
The problem I see here is we will still need to do some conditional statements.
To give more clarity lets say I have webpage with State Dropdown . With selection of different state will call the service api to get the master list of fruits and then for that list we apply our filters. Is there a way we can configure this.
LVL 36

Expert Comment

ID: 40503969
To give more clarity ....
That doesn't really give more clarity, because it just restates what you have already said.

we will still need to do some conditional statements
Well you need to tell us what these ADDITIONAL conditional statements are. The code I gave you handles the requirements that you stated in your previous comment, ie. "adding" fruits based on state and "removing" fruits based on state. If you have further conditional logic that needs to be applied, you have to tell us what it is.

Maybe the confusion lies in how to use the last piece of code that I gave you. Somewhere else in your code, you would have a method call that, as you put it, calls the service api to get the master list of fruit. This will result in a    List<Fruit fruitList             variable being populated. Also, you would (somehow) have retrieved the state that was selected in the dropdown and be holding that in some variable, ie.     String state          Now that you have those two items, you call the method that I gave you    processFruitsPerState     passing in the selected state as the String parameter and the master list of fruits as the List parameter. And the return value from that method is your filtered list with fruits added/deleted based upon the state that you passed it.

Perhaps though the confusion is in how the two Map's (addFruits and deleteFruits) are used/configured to apply the logic that you are after. I was hoping that the code comments that I put with those two lines of code would be enough to explain. But to give further detail I will say this, as in the example that you provided, if the state is Florida you want to add Oranges. So you put an entry in the "addFruits" map with the key "Florida" and the value is the set of Fruits to add, in this case just one, Oranges. This then gets handled by line 13 of what I posted, where I look up the addFruits map based on state and this returns the set of fruit to add, and then I add them to the main set of fruits. Because I am using a set, if Oranges are already there then nothing happens (you can only have one instance of a thing in a Set) otherwise if it's not there then it will be added.

And the same for deleting fruit, as in your example, if the state is "Texas" you want to delete Grapes. So you add an entry to "deleteFruits" map with the key "Texas" and the value is again a set of Fruit to delete. Again, in your case, you only want to delete one so you just have a set of Fruit with just Grapes in it. And then on line 14, we lookup deleteFruits map based on the state to get a set of Fruits to remove, and then remove any Fruits from the main set that are in that set returned. Again if a Fruit is NOT there then nothing happens, else if it is there it gets removed.

So the idea is that in addFruits map you have an entry for every state that you are dealing with, and for each of those state entries you have a Set of Fruit to add if that state is selected. The set of Fruit can have 0 elements (if you don't want to add anything extra), 1 element (to add 1 fruit) or X elements (and all X of them will be added). And the same for the deleteFruits map, you have an entry for every state, and then in each of those state entries you have the set of Fruit to delete (again the set could be 0, 1, or X elements in size)

Author Comment

ID: 40504015
Thanks for the explanation makes more sense to me.
LVL 36

Expert Comment

ID: 40504040
No worries, glad to help!

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question