Sorting Strings That Contains Number in Java

Sorting Strings that contains number in Java

Try this comparator, which removes all non-digit characters then compares the remaining characters as numbers:

Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}

int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});

Here's a test:

public static void main(String[] args) throws IOException {
List<String> strings = Arrays.asList("room1.2", "foo1.1", "foo", "room2.3", "room100.999", "room10", "room.3");

Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}

int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
System.out.println(strings);
}

Output:

[foo, room1, room2, room10, room100]

When the numbers are decimals (also demonstrating Java 8+ style):

public static void main(String[] args) {
List<String> strings = Arrays.asList("room1.2", "foo1.1", "room2.3", "room100.999", "room10", "room.3");
Collections.sort(strings, Comparator.comparing(Application::extractDouble));
System.out.println(strings);
}

static double extractDouble(String s) {
String num = s.replaceAll("[^\\d.]", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Double.parseDouble(num);
}

Result:

[foo, room.3, foo1.1, room1.2, room2.3, room10, room100.999]

Sorting a list of strings that contains numbers and letters

you can do it by using Comparator. With split("-") will seperate a single string where "-" are found and return a String[]. And then with the help of Integer.parseInt(((String) o).split("-")[0])), it will convert the first splitted String item to Integer and the Comparator can sort the list accordingly.

TOP10_Players.sort(Comparator.comparing((Object o) -> Integer.parseInt(((String) o).split("-")[0])));

Output: [1-Username1, 3-Username3, 5-Username2]

For descending order:

TOP10_Players.sort(Comparator.comparing((Object o) -> Integer.parseInt(((String) o).split("-")[0])).reversed());

Output: [5-Username2, 3-Username3, 1-Username1]

How do I sort strings that contain numbers in Java

  public static void main(String[] args)
{
String string = "3 42 \n 11 \t 7 dsfss 365 \r 1";
String[] numbers = string.split("\\D+");
Arrays.sort(numbers, new Comparator<String>()
{
public int compare(String s1, String s2)
{
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
});
System.out.println(Arrays.toString(numbers));
}

Sorting array of strings that contain number

You can do something like that:

list.sort(Comparator.comparing(YourClass::removeNumbers).thenComparing(YourClass::keepNumbers));

These are two methods:

private static String removeNumbers(String s) {
return s.replaceAll("\\d", "");
}

private static Integer keepNumbers(String s) {
String number = s.replaceAll("\\D", "");
if (!number.isEmpty()) {
return Integer.parseInt(number);
}
return 0;
}

For following data:

List<String> list = new ArrayList<>();
list.add("TEXT-2");
list.add("TEST-6");
list.add("TEST-1");
list.add("109");
list.add("TE");
list.add("TESTT-0");
list.add("TES-100");

This is the sorting result:

[109, TE, TES-100, TEST-1, TEST-6, TESTT-0, TEXT-2]

Sort on a string that may contain a number

The Alphanum Algorithm

From the website

"People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix it."

Edit: Here's a link to the Java Comparator Implementation from that site.

Sorting a String list with Integer values in Java

I suggest using biginteger because your numbers seems quite large. It's not the most efficient and optimized solution but yeah it will work

public static List<String> sortData(List<String> data){
List<BigInteger>convertedData=new ArrayList<BigInteger>();
for (String s : data)
{
//System.out.println(s);
convertedData.add(new BigInteger(s));
}
Collections.sort(convertedData);
List<String>sortedData=new ArrayList<String>();

for (BigInteger b : convertedData)
{
sortedData.add(String.valueOf(b));

}
return sortedData;
}

Your code:

JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);

for (int i = 0; i< jsArray.size(); i++) {
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
List<String> sortedData=sortData(data); **<------**

How to sort a string list consists of digits and alphabets in Java?

I assume that there will always be a pattern like:

"something something"

for all the values that the getValue() method returns

and that the 2nd "something" will always start with a number with or without trailing chars.

The code below splits every such value in 3 parts and compares

the 1st part alphabetically

the 2nd part numerically and

the 3d part alphabetically:

private List<Location> sortLocationList(List<Location> locationArrayList){
Collections.sort(locationArrayList, new Comparator<Location>(){
@Override
public int compare(Location o1, Location o2){
String s1 = o1.getValue();
String s2 = o2.getValue();

if (s1.equalsIgnoreCase(s2))
return 0;

String[] tokens1 = s1.split(" ");
String[] tokens2 = s2.split(" ");

if (!tokens1[0].equalsIgnoreCase(tokens2[0]))
return s1.compareToIgnoreCase(s2);

int number1 = Integer.parseInt(tokens1[1].replaceAll("\\D", ""));
int number2 = Integer.parseInt(tokens2[1].replaceAll("\\D", ""));

if (number1 != number2)
return number1 - number2;

String suffix1 = tokens1[1].replaceAll("\\d", "");
String suffix2 = tokens2[1].replaceAll("\\d", "");

return suffix1.compareToIgnoreCase(suffix2);
}
});

return locationArrayList;
}

How do I sort a list of string and numbers in numerical order?

Since your listId is String ,the list gets sorted lexographically. Instead you could first convert the String to an Integer and then sort it. Below is the illustration.

Collections.sort(tempList, (mainData, t1) -> Integer.parseInt(mainData.getListId())-Integer.parseInt(t1.getListId());


Related Topics



Leave a reply



Submit