Home > Software engineering >  java alternative to using nested for loops
java alternative to using nested for loops

Time:12-10

I have a Policies object with two fields: policyNumber and policyStatus. I will have a list of policies, and I need to see if any policy has one of the statuses I provide. If one does, I set a Boolean to yes. If not, I set it to no.

Normally I would use nested for loops like this:

Boolean hasStatus = false;
List<Policy> policies = new List<Policy>();
String[] statuses = String[]{'A1','A3','B6','T1','T6'};
for (Policy policy : policies) {
    for (int i=0; i<statuses.length; i  ) {
        if (policy.policyStatus == statuses[i] {
            hasStatus = true;
            break;
        }    
    }
}
return hasStatus;

Now I'm extremely week in the areas involving Maps, Sets and Collections and also in Algorithms. What I'm wondering is whether there is something with one of those things that I should be doing with this instead of using the nested for loops and the if block. If there is, could you please provide me some guidance on it? Or is this really how I should be doing this?

CodePudding user response:

Construct a Set<String> containing the statuses:

Set<String> statusSet = new HashSet<>(statuses);

Then use streams to iterate the policies:

return policies.stream().anyMatch(p -> statusSet.contains(p.policyStatus));

CodePudding user response:

You can implement your Policy class as a Map of policyStatus and policyNumber (in this scenario policyStatus is key policyNumber is value of Map) and and perform your checking like this:

    Boolean hasStatus = false;
    Map<String, Integer> policyMap = getPolicyMap();
    String[] statuses = String[]{"A1", "A3", "B6", "T1", "T6"};
    for (String status : statuses) {
        if(policyMap.get(status) != null){
            hasStatus = true;
            break;
        }
    }
    
    return hasStatus;

or if you can't do this and your statuses has constant length or has a small supremum on its length, you should not be worried about having a subroutine with nested loop on your project. because it's impossible. what you do is searching m element on array of n, without any prior condition or knowledge, you need O(nm) comparison, so you need nested loop. But as I said you can refactor your code with Map data structure and have single loop.

CodePudding user response:

There are a couple of issues I'd like to address before diving in.

List is an interface, so you can't instantiate an object of this type. You can use ArrayList to instantiate it however. You shouldn't have to access the members directly with policy.policyStatus, you should consider using a getter to ensure encapsulation, so policy.getStatus().

Use filters and maps! As Andy eloquently put it, that is a very clean and elegant solution. Hope this helps also!

Short addition: I think java streams are sometimes overcomplicated a little bit, but they are so incredibly useful. If you stream a collection with .stream(), that is making Java look through every single member of the collection one by one. Then you can use a bunch of cool methods.

...stream().map() just applies a function to the individual objects, one by one. This function can be anything! The function interface in java has one method R apply(T t); - so it takes an input, and produces an output. As you can see output of type R can be different to input of type T. If you don't want to return anything, you can use collections forEach method directly on the collection. This method takes a consumer, which is like a function but it doesn't return anything. You can also do ...stream().filter() which takes a predicate, basically a question that evaluates to true or false. All of this is just for simplicity of code, functional programming in java is actually super useful in the wild :D

  • Related