-2

I wanted to know how many males and females in my array. Using the words (M) and (F) as indicator. I currently have no idea how to do it.

Here's my array:

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};  
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3816246
  • 21
  • 1
  • 2

8 Answers8

9

In Java 8 you can do this.

String[] ppl = {"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
long male = Stream.of(ppl).filter(s -> s.endsWith("(M)")).count();
long female = Stream.of(ppl).filter(s -> s.endsWith("(F)")).count();

You can add .toUpperCase() if you don't know the case, and/or use .contains instead of .endsWith if you don't know where the (F) might be.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 2
    your ans is good demo of aggregate functions and lamdas but it hardly seems the user is even aware of java1.5/6 – Shailesh Aswal Jul 09 '14 at 08:53
  • 1
    If you can assume everyone is either male or female, `long female = ppl.length - male` would be quicker for long lists. – Holloway Jul 09 '14 at 08:56
  • 2
    @Shail016 I agree, and most likely this is homework the OP should be working out for themselves ;) but answering using Java 8 is more likely to be interesting to more people. – Peter Lawrey Jul 09 '14 at 08:58
  • @Trengot I didn't want to suggest a female is a "not male" or males are the ones worth counting. ;) – Peter Lawrey Jul 09 '14 at 09:00
  • 2
    @Shail016 I try to give an answer to homework questions which are both informatively but a student couldn't pass off as their own work. ;) – Peter Lawrey Jul 09 '14 at 09:01
2

Here is my solution:

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
int maleCount = 0;
for (String str : ppl) {
  if (str.trim().toUpperCase().endsWith("(M)")) {
    maleCount++;
  }
}

System.out.println("Male count: " + maleCount);
System.out.println("Female count: " + (ppl.length - maleCount));

Result:

Male count: 4
Female count: 2

Explanation: You now the size of input (array.length()). You just need to count all the Males (or Females) and other can be derived.

Ambrish
  • 3,627
  • 2
  • 27
  • 42
1

Here is the code sample -

public static void main(String[] args) {
    String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    int maleCount = 0;
    int femaleCount = 0;
    for (int i = 0; i < ppl.length; i++) {
        if(ppl[i].contains("(M)")){
            maleCount++;
        }
        if(ppl[i].contains("(F)")){
            femaleCount++;
        }
    }
    System.out.println("maleCount: "+maleCount);
    System.out.println("femaleCount: "+femaleCount);
    }

Output :

maleCount: 4
femaleCount: 2
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
1
String[] arr = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    int maleCount=0,femaleCount=0;
    for(String element : arr){
        if(element.endsWith("(F)")){
            femaleCount++;
            System.out.println(element +" is Female");
        }else if(element.endsWith("(M)")){
            maleCount++;
            System.out.println(element +" is Male");
        }
    }
    System.out.println("Total males "+maleCount +" Total Females "+femaleCount);
Jijo Mathew
  • 222
  • 1
  • 3
  • 9
1

Untested, but this should get you most of the way there. This isn't a hash like "Karen" => "F".. but the part ".substring(-3)" should count the occurences of (F) and (M).. have a look at this question

String[] arr = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
Integer counter = 0;
String lastItem = arr[0];
for(int i = 0; i < arr.length; i++)
{
    if(arr[i].substring(-3).equals(lastItem))
    {
        counter++;
    }
    else
    {
        itemCount.add(counter);
        counter = 1;
    }
    lastItem = arr[i];
}
itemCount.add(counter);
Integer[] Counts = itemCount.toArray(new Integer[itemCount.size()]);
Community
  • 1
  • 1
J-Dizzle
  • 3,176
  • 6
  • 31
  • 49
1

I've found this code easy to use and understand (no iteration needed):

String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
    String ss=Arrays.toString(ppl).replaceAll("[\\[\\]]", "");
    int malecount = ss.split("(M)").length - 1;
    int femalecount = ss.split("(F)").length - 1;

:)

Yashar Aliabbasi
  • 2,663
  • 1
  • 23
  • 35
0
  String[] ppl = new String[]{"Karen (F)","Kevin (M)","Lee (M)","Joan (F)","Des (M)","Rick (M)"};
      int k,m=0,f=0;
      for( k=0;k<ppl.length;k++)
      {
      if(ppl[k].contains("(F)"))
          f=f+1;
        if(ppl[k].contains("(M)"))
          m=m+1;  
      }
swapnil gandhi
  • 816
  • 1
  • 20
  • 38
0

Try to represent the data with classes and enums instead, so you seperate the name from the gender.

Define gender:

public enum Gender {
     MALE, FEMALE, SHEMALE_WTF;
}

Define a person:

public class Person {
    private String name;
    private Gender gender;

    public Person(String name, Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }
    public Gender getGender() {
        return gender;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
       return name;
    }

    public boolean isGender(Gender gender) {
       return this.gender == gender;
    }
}

Now we can create a person simply by writing:

Person karen = new Person("Karen", Gender.FEMALE);

Lets check if 'karen' is a male:

if(karen.isGender(Gender.MALE)) {
     //Ok, karen is a male
}
else {
     //karen is not a male
}

Lets create a Person array instead of your String array:

Person[] ppl = new Person[]{new Person("Karen", Gender.FEMALE),new Person("Kevin", Gender.MALE),new Person("Lee", Gender.MALE),new Person("Joan", Gender.FEMALE),new Person("Des", Gender.MALE),new Person("Rick", Gender.MALE)};

Now lets do the counting:

int females = 0;
int males = 0;


for(Person person : ppl) {
     switch(person.getGender()) {
         case Gender.MALE: 
              males++;
              break;
         case Gender.FEMALE:
              females++;
              break;
         case Gender.SHEMALE_WTF:
              //hmm?
              males++;
              females++;
              break;
              // but I would just:
              // throw new SecurityException("SYSTEM GOT VIRUS!!!!");

      }
 }

Now you have a code that is easy to read.