Home > Software design >  How to verify that the number of elements returned in a Java List is equal to a specified integer?
How to verify that the number of elements returned in a Java List is equal to a specified integer?

Time:03-28

Given this expression:

List <String> names = Arrays.asList("Jack", "Jones", "Jack", "Adam");

I want to verify that there are two Jacks on the List. So the intention is to store the two Jack elements in a variable and then use it in an assertion later.

I looped through names and it returns all names in the list as expected:

for(String theNames: names){
System.out.println(theNames);
}

but not sure how to proceed to filter only elements known as Jack, putting the result in a variable. How can I achieve this?

CodePudding user response:

Here is one way. Just filter for the target and count the occurences.

String target = "Jack";
List <String> names = Arrays.asList("Jack", "Jones", "Jack", "Adam");
long count = names.stream().filter(s->s.equals(target)).count();

System.out.printf("There are %d of the name '%s' in the list.%n", count, target); 

prints

There are 2 of the name `Jack` in the list

If case isn't important you can use equalsIgnoreCase in above. You can also test the count value against a specified quantity you are looking for.

A more traditional way would be as follows:

int count = 0;
for(String name : names) {
   if (name.equals(target) {
     count  ;
   }
}
  •  Tags:  
  • java
  • Related