I want to find the largest string value (alphabetically) in the following ArrayList. How to do that?
Code:
ArrayList <String> list = new ArrayList<String>();
list.add("ABC");
list.add("XYZ");
list.add("KLM");
Printable View
I want to find the largest string value (alphabetically) in the following ArrayList. How to do that?
Code:
ArrayList <String> list = new ArrayList<String>();
list.add("ABC");
list.add("XYZ");
list.add("KLM");
This might not be the best implementation, but this might give you an idea. I have used a StringBuffer in the code below because String is immutable. HTH
Code:import java.text.DateFormat;
import java.util.*;
public class LargestString
{
public static void main(String args[])
{
ArrayList <String> list = new ArrayList<String>();
list.add("ABC");
list.add("XYZ");
list.add("KLM");
StringBuffer largest = new StringBuffer("");
for(int i=0; i<list.size(); i++){
if(list.get(i).compareTo(largest.toString())>0){
largest.setLength(0);
largest.append(list.get(i));
}
}
System.out.println(largest.toString());
}
}
When you say the largest String value do you mean as in size, or do you mean as in b > a < c meaning alphabetical order? For that you would need something like this:
Note that what this code does is first convert the String to a charcter array, then adds their ASCII codes together, meaning that a = 97, while b = 98, b > a. You are going to get problems when it comes to capitals though, since a = 97, while CAPITAL B = 66 making it a > B. One solution is to just convert everything to lowercase before you check it. The other one is a little more complicated, it involves changing the for loops:Code:String a = "aaaaa";
String b = "bb";
char[] aAr = a.toCharArray();
char[] bAr = b.toCharArray();
int lenA = 0, lenB = 0;
for (int i = 0; i < aAr.length; i++) {
lenA += aAr[i];
}
for (int i = 0; i < bAr.length; i++) {
lenB += bAr[i];
}
System.out.println(lenA + " " + lenB);
What this does is simple:Code:String a = "a";
String b = "A";
char[] aAr = a.toCharArray();
char[] bAr = b.toCharArray();
int lenA = 0, lenB = 0;
for (int i = 0; i < aAr.length; i++) {
if (aAr[i] >= 90 || aAr[i] < 65)
lenA += aAr[i];
else
lenA += aAr[i] + 64;
}
for (int i = 0; i < bAr.length; i++) {
if (bAr[i] >= 90 || bAr[i] < 65)
lenB += bAr[i];
else
lenB += bAr[i] + 64;
}
System.out.println(lenA + " " + lenB);
It evaluates the character, if the character value is greater than 54 (so we cover in case there are numbers in the string, 1-9 or other chars) but less then 90, we assume that the value is a capital letter. Then we add to the size the value of the letter + 64, (twice the difference between the lowercase characters, and the uppercase characters).
Thanks to both of use. I have implemented your code and got the required results.
I learned new stuff.
Keep posting.