-1

If I have an array of names, how do I check if they all start with an upper case letter using forall (or something else functional)?

String[] names = {"Linda", "Peter", "Carol", "Paul"};
names.forall(name -> Character.isUpperCase(name.charAt(0))); 

that is wrong and I'm not really familiar with higher order functions yet so I could use some help.

Jazib
  • 1,343
  • 13
  • 27
s.r.y.
  • 11
  • 1
  • `names` is an array, and there is no `forall` method on arrays. – Andreas Sep 25 '19 at 22:04
  • You are trying to use forEach function in Java, right? Then use this: ```public static void main(String []args){ String[] names = {"Linda", "Peter", "Carol", "Paul"}; for(String myName : names){ if(Character.isUpperCase(myName.codePointAt(0))){ System.out.println(myName); } } }``` – ken4ward Sep 25 '19 at 22:23

2 Answers2

1

Use Stream.allMatch:

String[] names = {"Linda", "Peter", "Carol", "Paul"};
boolean allUpper = Arrays.stream(names).allMatch(name -> Character.isUpperCase(String.codePointAt(0)));
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
1

In Java 8+:

Arrays.stream(names).allMatch(name -> Character.isUpperCase(name.codePointAt(0)));

Or:

Stream.of(names).allMatch(name -> Character.isUpperCase(name.codePointAt(0)));

Note that I replaced charAt(0) with codePointAt(0) so it supports Unicode characters in the supplemental planes.

Andreas
  • 154,647
  • 11
  • 152
  • 247