Return 2 counted values from one function

You can call below method from your main function or any method. it will return a map of desired value. in below code i am assuming that persons is a list. but if person is an array, change size() with length method.

public HashMap<String,Integer>  countBoysAndWomen() {

        int womenCounter = 0;
        int boysCounter = 0;
        HashMap<String,Integer> hm = new HashMap<>();
        for (int i = 0 ; i < persons.size() ; i++ ) {

            if (p.isAdult() && p.isFemale()){
              womenCounter++;
            }
            else if (p.isChild() && p.isMale()) {
            boysCounter++;
            }
        }
         hm.put("women",womenCounter );
         hm.put("boy" , boysCounter);

         return hm;
     }

for retrieving hashmap value :-

 for (Map.Entry<String,String> entry : hm.entrySet())  
            System.out.println("Key = " + entry.getKey() + 
                             ", Value = " + entry.getValue()); 
    } 

Tags:

Java