Question

In java Write and test a method that finds the longest string(s) in a list of...

In java

Write and test a method that finds the longest string(s) in a list of strings. If there is more than one string with the maximum length, ALL of them should be returned, in some appropriate data-structure.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AllLongest {

    public static List<String> getAllLongest(List<String> strings) {
        List<String> longest = new ArrayList<>();
        for (int i = 0; i < strings.size(); i++) {
            if (longest.isEmpty() || longest.get(0).length() < strings.get(i).length()) {
                longest.clear();
                longest.add(strings.get(i));
            } else if (longest.get(0).length() == strings.get(i).length()) {
                longest.add(strings.get(i));
            }
        }
        return longest;
    }

    public static void main(String[] args) {
        System.out.println(getAllLongest(Arrays.asList("hi", "hello", "there", "how", "are", "you?")));
    }
}
Add a comment
Know the answer?
Add Answer to:
In java Write and test a method that finds the longest string(s) in a list of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT