How to modify a java list based on rules efficiently

Posted on 2014-12-15
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
  • 4
  • 3
LVL 35

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 =;

    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 35

Accepted Solution

mccarl earned 500 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.
Create the perfect environment for any meeting

You might have a modern environment with all sorts of high-tech equipment, but what makes it worthwhile is how you seamlessly bring together the presentation with audio, video and lighting. The ATEN Control System provides integrated control and system automation.


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 35

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 35

Expert Comment

ID: 40504040
No worries, glad to help!

Featured Post

Connect further...control easier

With the ATEN CE624, you can now enjoy a high-quality visual experience powered by HDBaseT technology and the convenience of a single Cat6 cable to transmit uncompressed video with zero latency and multi-streaming for dual-view applications where remote access is required.

Question has a verified solution.

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

Suggested Solutions

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This video teaches viewers about errors in exception handling.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

831 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