w3resource

Java Program: Lambda expression for checking uppercase, lowercase, or mixedcase strings

Java Lambda Program: Exercise-22 with Solution

Write a Java program to implement a lambda expression to check if a list of strings are all uppercase or all lowercase or mixedcase.

Sample Solution:

Java Code:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Function;

public class Main {
  public static void main(String[] args) {
    List < String > strings = Arrays.asList("Java", "JAVA", "java");
    System.out.println("Array elements: " + strings);
    // Check if the list is all uppercase using lambda expression
    boolean isAllUppercase = checkCase(strings, s -> s.equals(s.toUpperCase()), String::toUpperCase);
    System.out.println("Is all uppercase? " + isAllUppercase);

    // Check if the list is all lowercase using lambda expression
    boolean isAllLowercase = checkCase(strings, s -> s.equals(s.toLowerCase()), String::toLowerCase);
    System.out.println("Is all lowercase? " + isAllLowercase);

    // Check if the list is mixed case
    boolean isMixedCase = !isAllUppercase && !isAllLowercase;
    System.out.println("Is mixed case? " + isMixedCase);

    List < String > strings1 = Arrays.asList("JAVA", "PYTHON", "ABC");
    System.out.println("\nArray elements: " + strings1);
    // Check if the list is all uppercase using lambda expression
    isAllUppercase = checkCase(strings1, s -> s.equals(s.toUpperCase()), String::toUpperCase);
    System.out.println("Is all uppercase? " + isAllUppercase);

    // Check if the list is all lowercase using lambda expression
    isAllLowercase = checkCase(strings1, s -> s.equals(s.toLowerCase()), String::toLowerCase);
    System.out.println("Is all lowercase? " + isAllLowercase);

    // Check if the list is mixed case
    isMixedCase = !isAllUppercase && !isAllLowercase;
    System.out.println("Is mixed case? " + isMixedCase);

    List < String > strings2 = Arrays.asList("java");
    System.out.println("\nArray elements: " + strings2);
    // Check if the list is all uppercase using lambda expression
    isAllUppercase = checkCase(strings2, s -> s.equals(s.toUpperCase()), String::toUpperCase);
    System.out.println("Is all uppercase? " + isAllUppercase);

    // Check if the list is all lowercase using lambda expression
    isAllLowercase = checkCase(strings2, s -> s.equals(s.toLowerCase()), String::toLowerCase);
    System.out.println("Is all lowercase? " + isAllLowercase);

    // Check if the list is mixed case
    isMixedCase = !isAllUppercase && !isAllLowercase;
    System.out.println("Is mixed case? " + isMixedCase);

  }
  public static boolean checkCase(List < String > strings, Predicate < String > checkFunction, Function < String, String > convertFunction) {
    String firstString = strings.get(0);
    String convertedString = convertFunction.apply(firstString);

    return strings.stream()
      .allMatch(s -> checkFunction.test(s));
  }
}

Sample Output:

Array elements: [Java, JAVA, java]
Is all uppercase? false
Is all lowercase? false
Is mixed case? true

Array elements: [JAVA, PYTHON, ABC]
Is all uppercase? true
Is all lowercase? false
Is mixed case? false

Array elements: [java]
Is all uppercase? false
Is all lowercase? true
Is mixed case? false

Explanation:

In the above exercise -

The main() method:

  • Creates a list of strings named strings.
  • Calls the checkCase method to perform case checks and prints the results.

The checkCase() method:

  • Takes three parameters: the list of strings to check, a Predicate<String> to define the case check condition, and a Function<String, String> to convert the first string for comparison.
  • Retrieves the first string from the list using strings.get(0) and assigns it to firstString.
  • Apply the conversion function convertFunction to firstString and assign the result to convertedString.
  • Use the stream() method in the strings list to create a stream of strings.
  • Apply the allMatch intermediate operation on the stream and provide a lambda expression as the condition to check if all strings satisfy the given predicate checkFunction.
  • Returns the result of the allMatch operation, which indicates whether all strings in the list pass the case check.

Flowchart:

Flowchart: Java  Exercises: Sort list of objects with lambda expression.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Lambda Exercises Previous: Calculate sum of prime numbers with lambda expression.
Java Lambda Exercises Next: Lambda expression to find average string length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Hashset vs Treeset:

HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.

HashSet

  • the class offers constant time performance for the basic operations (add, remove, contains and size).
  • it does not guarantee that the order of elements will remain constant over time
  • iteration performance depends on the initial capacity and the load factor of the HashSet.
  • It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.

TreeSet

  • guarantees log(n) time cost for the basic operations (add, remove and contains)
  • guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via its constructor) (implements SortedSet)
  • doesn't offer any tuning parameters for iteration performance
  • offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc

Important points:

  • Both guarantee duplicate-free collection of elements
  • It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
  • None of these implementations are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
  • LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however,it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.

So a choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.

  • e.g. SortedSet<String> s = new TreeSet<String>(hashSet);

Ref: https://bit.ly/3d3waGh

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook