Longest string in arraylist java

Java: How to find Longest String in ArrayList ? [FUNCTION]

While I was playing with Java code, I have coded a class that has method that finds longest String in the ArrayList. Method is very simple, but I am sure that some of you will find it useful.

// I have a class attribute: private ArrayList wordsList = new ArrayList(); // here is method itself: public String longest_word() < String longest_word=""; int maxLength=0; for(int i=0; i if(wordsList.get(i).length() > maxLength)< maxLength = wordsList.get(i).length(); longest_word = wordsList.get(i); >> return longest_word; >

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion Cancel Reply

Discussion

It’s better to use iterators for this type of work. Because if your array is a LinkedList instance, using get(i) will have a negative effect on performance.

If you are using JDK 6 – you can use short for-statement:
[sourcecode language=”java”]
for(String w: wordList) if( w.length() > maxLength ) maxLength = w.length();
>
[/sourcecode]

this works too public int maxLength(ArrayListlist) <
int max=0;
for(int i=0; i if(list.get(i).length() max=list.get(i).length();
> >
return max;
>

Источник

Find longest length string in list

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.

Setup

ListString> randomStrings = new ArrayList<>(); @Before public void setUp()  randomStrings.add("XVxOPHS"); randomStrings.add("ttnBGouocZ"); randomStrings.add("yHYQbXq"); randomStrings.add("fkanCo"); randomStrings.add("cxBuL"); >

Straight up Java

In a traditional approach we will capture the first element in the list length setting it to a variable named longestString . Next we will iterate over a list checking each element and comparing it to the longestString length. If the length is greater than the previous we will set the longestString element to the current element. Finally in a junit assert we will validate that the longest length is equal to «ttnBGouocZ».

public void longest_string_java()  String longestString = randomStrings.get(0); for (String element : randomStrings)  if (element.length() > longestString.length())  longestString = element; > > assertEquals("ttnBGouocZ", longestString); >

Java 8

Using a java 8 lambda expression, we will create a java Comparator that will check the length of string which would make the list ascending. Converting a list to a stream calling sorted we will pass the comparator which will return the longest string first. Finally, calling the findFirst will return the first element wrapped in Optional.

@Test public void longest_string_sort_java8()  OptionalString> longest = randomStrings.stream() .sorted((e1, e2) -> e1.length() > e2.length() ? -1 : 1) .findFirst(); assertEquals("ttnBGouocZ", longest.get()); >

Google Guava

Using guava fluent ordering class we will compare the length of the strings and pass the ordering object to Collections.sort reversing the order of the comparator. In our assert we will use the Iterables.getFirst to retrieve the first element in the list.

public void longest_string_guava()  OrderingString> byLength = new OrderingString>()  public int compare(String left, String right)  return Ints.compare(left.length(), right.length()); > >; Collections.sort(randomStrings, byLength.reverse()); assertEquals("ttnBGouocZ", Iterables.getFirst(randomStrings, "")); >

Find longest length string in list posted by Justin Musgrove on 26 September 2014

Tagged: java and java-collections

Источник

How to find the longest string object in an arrayList

Note : if there is more than one word with the longest length then this method will simply Return the first word which is found with that length. Solution 2: Assuming your Word class has a method called length() , maybe something like this: Solution 3: For Java Stream enthusiasts one very declarative solution is: makes sure the stream skips over null values.

How to find the longest string object in an arrayList

Here is is my problem, I have to explain a lot, because it’s a quite complicated.

I have created an arrayList < Word >, that contains strings as objects. In my case, I have three classes, all working together, that is supposed to represent a dictionary.

The first class is called «Word», it has a constructor, and has simple methodes like .length, adds 1 to the counter, and keeps track of the words that are repeated.

The second class is called «wordlist», and uses more advanced methodes like reading a file, a summary of 30,000 words. Some methodes is for instance, to add words to the arraylist, as objects. Methods like search if they can find a perticular word. Now, these tasks contains parametres, with variables that I can use.

But I came upon a task in which I had to find the longest word(string) in the arrayList, without any parameters. The method is called: public Word findLongest().

In the thrid class, I have the test case, where I use the methodes. The most central part here is to read the file, and add it to the arrayList object. In what way can I use the method to find the longest word(string) in the arrayList without any parameters?

It is very confusing with arrayList as objects.

I am aware of the for (each : array) use in this sense, but have no idea how use it properly.

If your Word class provides a length() method which simply returns the length of the word represented by that object, then you can run through your ArrayList and find the longest like this:

private Word getLongestWordFromList(List listOfWords) < Word longestWord = null; for (Word word : listOfWords) < if (longestWord == null || word.length() >longestWord.length()) < longestWord = word; >> return longestWord; > 

The for (Word word : listOfWords) pattern simply says: iterate through the List called «listOfWords» and store the current Word object in a variable called «word». Then you just check the length of each word to see whether it is longer than the longest already found. (If the longestWord variable is null then it means you haven’t processed any words so far, so whatever is the first Word found will go into that variable, ready to be compared with the next.)

Note : if there is more than one word with the longest length then this method will simply Return the first word which is found with that length. If you need to return a list of all words having the longest length then you’ll need to modify this pattern to generate a List which contains all words of the longest length.

Assuming your Word class has a method called length() , maybe something like this:

Word longest = arrayList.get(0); for (int i=1; i longest.length()) < longest = arrayList.get(i); >> 

For Java Stream enthusiasts one very declarative solution is:

private Word getLongestWordFromList(List listOfWords) < return listOfWords.stream() .filter(word ->word != null) .max(Comparator.comparing(Word::length)) .orElse(null); > 

filter makes sure the stream skips over null values.

max compares the word lengths and returns an Optional with the largest length value. Note that instead of Word::length we could have also written word -> word.length() .

orElse «unpacks» the optional value. If it didn’t find anything (eg. because every value is null or listOfWords is empty), it returns null .

Find the longest word/string in an array, At that point, you can grab the first item. Note however that there may be other strings immediately following the first that are of the same length. As for your above code, longest is declared as a number, but later set to a string. The number we’re interested in comes from the length of the string. Our condition …

Find the longest String in an array recursively

public static String rMax(String[] s)< if (s.length == 1)< return s[0]; >else < String[] newArray = Arrays.copyOfRange(s, 1, s.length); String maxInNewArray = rMax(newArray); String currentString = s[0]; if(currentString.length() >maxInNewArray.length()) < return currentString; >else return maxInNewArray; > > 

The above code works but I am looking for an alternative way of coding this one instead of using Arrays.copyOfRange(). Any help is appreciated.

You could just add a helper adding a start position to consider, avoiding the copy:

public static String rMax(String[] s) < return rMax(s, 0) >public static String rMax(String[] s, int start)< if (start + 1 == s.length)< return s[start]; >else < String maxInNewArray = rMax(s, start + 1); String currentString = s[start]; if(currentString.length() >maxInNewArray.length()) < return currentString; >else return maxInNewArray; > > 

Find the longest String in an array recursively, Find centralized, trusted content and collaborate around the technologies you use most. Learn more

How to get the longest string in an array using JavaScript ?

The task is to get the longest string from the array. Here a few of the most used techniques discussed with the help of JavaScript. In this article, we will use two JavaScript methods sort() method and the reduce() method to find out the longest string the array. Both the approach are described below with the example.

Approach 1: In this approach we will use .sort() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. If the answer is positive then ‘b’ is greater else ‘a’ is greater. This method arranges the elements in the decreasing order of their length and we can access the first element by [0].

    Example: This example implements the above approach.

Источник

How to find the longest string object in an arrayList

Here is is my problem, I have to explain a lot, because it’s a quite complicated.

I have created an arrayListWord>, that contains strings as objects. In my case, I have three classes, all working together, that is supposed to represent a dictionary.

The first class is called “Word”, it has a constructor, and has simple methodes like .length, adds 1 to the counter, and keeps track of the words that are repeated.

The second class is called “Wordlist”, and uses more advanced methodes like reading a file, a summary of 30,000 words. Some methodes is for instance, to add words to the arraylist, as objects. Methods like search if they can find a perticular word. Now, these tasks contains parametres, with variables that I can use.

But I came upon a task in which I had to find the longest word(string) in the arrayList, without any parameters. The method is called: public Word findLongest().

In the thrid class, I have the test case, where I use the methodes. The most central part here is to read the file, and add it to the arrayList object. In what way can I use the method to find the longest word(string) in the arrayList without any parameters?

It is very confusing with arrayList as objects.

I am aware of the for (each : array) use in this sense, but have no idea how use it properly.

Answer

If your Word class provides a length() method which simply returns the length of the word represented by that object, then you can run through your ArrayList and find the longest like this:

private Word getLongestWordFromList(List listOfWords) < Word longestWord = null; for (Word word : listOfWords) < if (longestWord == null || word.length() >longestWord.length()) < longestWord = word; >> return longestWord; >

The for (Word word : listOfWords) pattern simply says: iterate through the List called “listOfWords” and store the current Word object in a variable called “word”. Then you just check the length of each word to see whether it is longer than the longest already found. (If the longestWord variable is null then it means you haven’t processed any words so far, so whatever is the first Word found will go into that variable, ready to be compared with the next.)

Note: if there is more than one word with the longest length then this method will simply return the first word which is found with that length. If you need to return a list of all words having the longest length then you’ll need to modify this pattern to generate a List which contains all words of the longest length.

Источник

Читайте также:  Text to lowercase css
Оцените статью