Solved

How to modify a java list based on rules efficiently

Posted on 2014-12-15
7
149 Views
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?
0
Comment
Question by:greenearth
  • 4
  • 3
7 Comments
 
LVL 35

Expert Comment

by:mccarl
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.
0
 

Author Comment

by:greenearth
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.
0
 
LVL 35

Accepted Solution

by:
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
    fruitSet.addAll(originalFruits);

    fruitSet.addAll(addFruits.get(state));
    fruitSet.removeAll(deleteFruits.get(state));

    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.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:greenearth
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.
0
 
LVL 35

Expert Comment

by:mccarl
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)
0
 

Author Comment

by:greenearth
ID: 40504015
Thanks for the explanation makes more sense to me.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 40504040
No worries, glad to help!
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
changeXy challenge 13 58
network + 7 73
HashMap Vs TreeMap 12 49
Re-position sub-options beneath the TAB 7 43
This article will show, step by step, how to integrate R code into a R Sweave document
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

747 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now