Determine the long, longer and longest ArrayList of Strings

find longest string in arraylist java
find longest string in array java
how to find the longest word in a string in java
how to find the longest string in an array javascript
find the longest string in an array python
java longest string possible
find longest string in array c#
find longest string in vector c++

I have three (3) ArrayLists of different sizes and I want to know which is the long, longer and longest. I came up with this solution which works fine, but it doesn't look optimised enough. I will like someone to optimise it for me. Thanks in advance.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LongLongerLongest {


    public static void main(String[] args){

        /**
         * Generated ArrayLists for testing
         */
        List<String> first = Arrays.asList("qw", "sd", "asw");
        List<String> second = Arrays.asList("qw", "sd", "r4", "asw", 
"qw", "sd", "r4", "asw", "r4", "asw");
        List<String> third = Arrays.asList("qw", "sd", "r4", "asw", 
"r4", "asw", "oiu");


        String result = sortLists(first,second, third);
        System.out.println(result);
    }



    static String sortLists(List<String> firstList, List<String> 
secondList, List<String> thirdList) {

        /**
         * declare a list to hold all sizes
         */
        List<Integer> listOfSizes = new ArrayList<>();

        List<String> longList;
        List<String> longerList;
        List<String> longestList;

        /**
         * Add the size of all array to the listOfSizes list and sort
         */
        listOfSizes.add(firstList.size());
        listOfSizes.add(secondList.size());
        listOfSizes.add(thirdList.size());
        Collections.sort(listOfSizes);

        /**
         * Searching for the longest
         */
        if (firstList.size() == listOfSizes.get(2)) {
            longestList = firstList;
        }
        else if (secondList.size() == listOfSizes.get(2)) {
            longestList = secondList;
        } else {
            longestList = thirdList;
        }

        /**
         * Searching for the longer
         */
        if (firstList.size() == listOfSizes.get(1)) {
            longerList = firstList;
        }
        else if (secondList.size() == listOfSizes.get(1)) {
            longerList = secondList;
        } else {
            longerList = thirdList;
        }

        /**
         * Searching for the long
         */
        if (firstList.size() == listOfSizes.get(0)) {
            longList = firstList;
        }
        else if (secondList.size() == listOfSizes.get(0)) {
            longList = secondList;
        } else {
            longList = thirdList;
        }

        String result = "long: " + longList.toString() + ", longer: " + 
longerList.toString() + ", longest: " + longestList.toString();
        return result;
    }

}

What I have above is in a bid to find the intersection of the three. But for error handling I have decided to sort from the largest down to avoid empty lists.

To optimized for minimum amount of code, use streams:

public static String sortLists(List<String> firstList, List<String> secondList, List<String> thirdList) {
    List<List<String>> sorted = Stream.of(firstList, secondList, thirdList)
            .sorted(Comparator.comparingInt(List::size))
            .collect(Collectors.toList());
    return "long: " + sorted.get(0) + ", longer: " + sorted.get(1) + ", longest: " + sorted.get(2);
}

For a pre-Java 8 solution, you can do it like this:

public static String sortLists(List<String> firstList, List<String> secondList, List<String> thirdList) {
    @SuppressWarnings("unchecked")
    List<String>[] lists = new List[] { firstList, secondList, thirdList };
    Arrays.sort(lists, new Comparator<List<?>>() {
        @Override
        public int compare(List<?> list1, List<?> list2) {
            return list1.size() - list2.size();
        }
    });
    return "long: " + lists[0] + ", longer: " + lists[1] + ", longest: " + lists[2];
}

String's Maximum length in Java - calling length() method, How do you find the largest string in an ArrayList? Java String array FAQ: Can you share an example of how to determine the largest String in a Java String array?. Sure, in this short tutorial I’ll share the source code for a complete Java class with a method that demonstrates how to find the longest String in a Java string array.

Here is a Stream API approach to reducing the amount of code:

static String sortLists(List<String> firstList, List<String> secondList, List<String> thirdList) {
     return Stream.of(firstList, secondList, thirdList)
                  .sorted(Comparator.comparingInt(List::size))
                  .collect(collectingAndThen(toList(), f -> "long: " + f.get(0) + ", longer: " +
                         f.get(1) + ", longest: " + f.get(2)));
}

create a stream from the three lists, then sort by their sizes and then finally apply a finishing function to get the expected format.

imports required:

import static java.util.stream.Collectors.*;
import java.util.stream.*;

Finding Largest String in ArrayList, How do you find the length of a string in an array? This example will show how get the maximum length string in an arraylist using java, java 8 and guava. In the set up we will initialize an arraylist of random strings.In a comparable example we demonstrate how to find the maximum length string in a collection using groovy.

If you can use Java 8, i would recommend an approach using the Stream API.

If you want an approach with arbitary types:

public static List<List<?>> sortBySize(List<?>... lists) {
    return Arrays.stream(lists).sorted(Comparator.comparing(List::size))
            .collect(Collectors.toList());
}

Using a generic type parameter if the lists are of the same type:

@SafeVarargs
public static <T> List<List<T>> sortBySize(List<T>... lists) {
    return Arrays.stream(lists).sorted(Comparator.comparing(List::size))
            .collect(Collectors.toList());
}

Java: How to find the longest String in an array of Strings , Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly. import java.util.Scanner; import  This example will show how get the minimum length string in an arraylist using java, java 8 and guava. In the set up we will initialize an arraylist of random Presidents of the United States . In a comparable example we demonstrate how to find the shortest length string in a collection using groovy .

7.10. Code Practice with ArrayLists, Sure, in this short tutorial I'll share the source code for a complete Java class with a method that demonstrates how to find the longest String in a  Find the length of each string in str. Use strlength, not length, to determine the number of characters in each element of a string array.

Big Java: Compatible with Java 5, 6 and 7, The code should instantiate an ArrayList of Strings names and fill it with the Strings from 1. import java.util.list;. 2. import java.util.ArrayList;. 3. ​. 4. public class Test. 5 in ArrayList list and removes any that are strictly longer than 4 characters. findLongest to find and return the longest String in the ArrayList of Strings list . Sort strings, length. Strings can be sorted based on their lengths. We put the shortest string first and the longest string last. This algorithm doesn't need to be fast, but it should not create problems. We sort strings by their Length property.Sort String Length

ArrayListExamples.java, R7.4 Write a loop that reads 10 strings and inserts them into an array list. R7.5 Consider the algorithm that we used for determining the maximum value in an array list. We set largestYet to the starting element, which meant that we were no longer Modify the loop that finds the bank account with the largest balance, using  Hi I've done quite a bit of searching today but no luck, I am looking to sort the list of words in an arraylist by the size of the "String" arraylist contains dog, car, dude, football it should but football at the start etc I've tried using Arrays.sort() but no luck. thank you

Comments
  • "Optimised" in what way? Performance? Amount of code? Code complexity? Storage used? Something else?
  • A naive way to do that would be a List<List<String>> which you sort by using a Comparator<List<String>> to compare list sizes.
  • @Andreas , Amount of code. The If(s) seems too much.
  • Define "long" and "longer".
  • Is there a point in using wildcards in your second example when you still use the specific generic types the parameters? I would either define every generic as String or only use wildcard (when you can also remove the SuppressWarnings annotation), but not mix that.
  • @Tom I used wildcards in Comparator to type less code and make it more generic. I didn't use wildcards in sortLists method, to retain the method signature given in the question.