Get the Max value of characters Java

Viewed 103

Im trying to get the max number of characters from sql table.

Example: lorem ipsum - 11 characters; lorem ipsum dolor - 17 characters; => max = 17;

For now i can get the number of characters for each column:

 while (rs2.next()) {
            nume = rs2.getString(1);
            CNP = rs2.getString(2);
            adresa = rs2.getString(3);
            String[] arr = { nume, CNP, adresa };
            int max = maxLength(arr);

 static int maxLength(String[] arr) {
    int len = 0;
    int N = arr.length;
    List<String> list = new ArrayList<String>();   
    // Traverse the array
    for (int i = 0; i < N; i++) {
        // Stores the length of current String
        int l = arr[i].length();
        // Update maximum length
        if (len < l) {
            len = l;
        }
    }

    // Return the maximum length
    return len;
}
3 Answers

You have to add a variable above the while() loop: int maxOfLength = 0;. Then, below the int max = maxLength(arr); you should compute the max length of all rows from the table in the following way:

if (max > maxOfLength) {
    maxOfLength = max;
}

After executing the while loop you'll have the max length of all strings in your whole table.

The following will give you the max characters that a column can have in your result set.

  int max = 0; <-------------------
  while (rs2.next()) {
            nume = rs2.getString(1);
            CNP = rs2.getString(2);
            adresa = rs2.getString(3);
            String[] arr = { nume, CNP, adresa };
            int k = maxLength(arr);
            if (k > max){
              max = k;
             }
     }
   
    return max;

 static int maxLength(String[] arr) {
    int max = 0;
    int N = arr.length;
    List<String> list = new ArrayList<String>();   
    // Traverse the array
    for (int i = 0; i < N; i++) {
        // Stores the total length
        int len =  arr[i].length(); <----------
        if (len > max){ 
          max = len;
          }
    }

Use Streams

Using streams will result in clear solution without having to worry about variables and incorrect comparisons

        String[] elements = {"lorem ipsum", "lorem ipsum dolor"};
        System.out.println(Arrays.stream(elements).mapToInt(e -> e.length()).max());

Related