0

I have an array of Strings and I want to fill another array with the largest Strings of the aforementioned array. I can get the size of the array correctly and fill it with the correct amount of variables, but two of the variables are null while the third is the correct value.

public static void main(String[] args) {
    String[] inputArray = {"aba", "aa", "ad", "vcd", "123"};
    String[] resultsArray = allLongestStrings(inputArray);


    for(String x: inputArray) {
        System.out.println("Input array: " + x);
    }

    for(String temp: resultsArray) {
        System.out.println("Results array: " + temp);
    }
}

public static String[] allLongestStrings(String[] inputArray) {
    int len = 0;
    for(String temp: inputArray) {
        if(temp.length() > len) {
            len = temp.length();
        }
    }
    String[] ret = new String[len];

    for(int i = 0; i <= inputArray.length-1; i++) {
        if(inputArray[i].length() == len) {
            ret[ret.length-1] = inputArray[i];
        }
    }


    return ret;
}

my results are:

Input array: aba

Input array: aa

Input array: ad

Input array: vcd

Input array: 123

Results array: null

Results array: null

Results array: 123

How can I get the two null values to become aba and vcd?

5 Answers 5

2

You have to count the number of elements that are of that length. Currently, your code allocates a result array with len number of elements. The length of the longest string (len in your code) has nothing to do with the number of strings of that length.

public static String[] allLongestStrings(String[] inputArray) {
    int len = 0;
    int num = 0;
    for (String temp : inputArray) {
        if (temp.length() == len) {
            num++;
        } else if (temp.length() > len) {
            len = temp.length();
            num = 1;
        }
    }

    String[] ret = new String[num]; // <-- allocate the right number of elements

    for (int i = 0, j = 0; i <= inputArray.length - 1; i++) {
        if (inputArray[i].length() == len) {
            ret[j++] = inputArray[i];
        }
    }
    return ret;
}

It iterates through the array checking for the longest string while maintaining the number of elements of the longest string we have seen so far. After the first iteration, you would know the number of elements that would make into the result array and hence you can allocate the right size and populate it.


Another fun way to do this using Java streams:

public static String[] allLongestStrings(String[] inputArray) {
    TreeMap<Integer, List<String>> lengthToStrings = Arrays.stream(inputArray)
            .collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));

    return lengthToStrings.lastEntry()
            .getValue()
            .toArray(new String[0]);
}

The first part constructs a TreeMap that has the mapping from the length of a String to the list of strings of that length. Since, it is ordered by the Integer's natural ordering (ascending order), we can get the max length by reading the last entry. That entry, would have all the strings of that length.

The last part converts the List<String> to a String[] and returns it.

Sign up to request clarification or add additional context in comments.

2 Comments

Why not put an else-if in the first loop? if (temp > len) { len = temp.length(); num = 1; } else if (temp == len){ num++;}
@Eritrean You are right. We can avoid 2nd iteration. Updated the answer :)
0

There are a couple of issues with you code:

  1. The size of the ret array isn't related to the actual max length len.
  2. You're just adding elements to the last index of ret array:
ret[ret.length-1] = inputArray[i];

So, for the first issue, you might want to keep a count of max length strings in the original array, and address the second by using proper index pointers:

public static String[] allLongestStrings(String[] inputArray) {
    int len = 0, count = 0;
    for(String temp: inputArray) {
        if (temp.length() > len) {
            len = temp.length();
            count = 1;           // new max length, so reset count to 1
        } else if (temp.length() == len) {
            count++;
        }
    }
    String[] ret = new String[count];

    for(int i = 0, j = 0; i < inputArray.length; i++) {
        if (inputArray[i].length() == len) {
            ret[j++] = inputArray[i];
        }
    }

    return ret;
}

Comments

0

Short Java 8 version:

    String[] inputArray = {"aba", "aa", "ad", "vcd", "123"};

    // find out the biggest element size
    Optional<String> biggest = asList(inputArray).stream().max(Comparator.comparing(String::length));

    // filter only element that contains the same size as the biggest one
    List<String> bigOnes = asList(inputArray).stream()
            .filter(element -> element.length() == biggest.map(String::length).orElse(0))
            .collect(Collectors.toList());

    // print them
    bigOnes.forEach(System.out::println);

Comments

0

Ignoring the fact that the number of elements matching the max len is not properly calculated (but by chance, in your use case, the max length match the number of elements of that length i.e. 3). You may use a List to remove the size constraint and returns retList.toArray() if you really need an array.

Back to the real issue, you're not filling up the ret array properly. You need to keep track of the index instead of always using the length -1 :

   for(int j=0,i = 0; i <= inputArray.length-1; i++) { // <-- See j declared here
        if(inputArray[i].length() == len) {
            ret[j++] = inputArray[i]; // <--- See j++ usage instead of ret.length -1
        }
    }

Cheers!

Comments

0

Here is the single loop solution.

public static String[] allLongestStrings(String[] inputArray) {
    int len = 0;
    ArrayList<String> ret = new ArrayList<>(inputArray.length);
    for(String temp: inputArray) {
        if(temp.length() > len) {//reset list as bigger length is found.
            len = temp.length();
            ret.clear();
            ret.add(temp);
        }else if(temp.length()==len){//accumulate all longest Strings in the list
            ret.add(temp);
        }
    }
    return ret.toArray(new String[0]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.