Array.sort not sorting all element [duplicate] - java

I have String[] array like
{"3","2","4","10","11","6","5","8","9","7"}
I want to sort it in numerical order, not in alphabetical order.
If I use
Arrays.sort(myarray);
I obtain
{"10","11","2","3","4","5","6","7","8","9"}
instead of
{"2","3","4","5","6","7","8","9","10","11"}

Try a custom Comparator, like this:
Arrays.sort(myarray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
Hope you like it!

I think by far the easiest and most efficient way it to convert the Strings to ints:
int[] myIntArray = new int[myarray.length];
for (int i = 0; i < myarray.length; i++) {
myIntArray[i] = Integer.parseInt(myarray[i]);
}
And then sort the integer array. If you really need to, you can always convert back afterwards:
for (int i = 0; i < myIntArray.length; i++) {
myarray[i] = "" + myIntArray[i];
}
An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.

I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:
The Alphanum Algorithm
There is a Java implementation example linked from the article.
With that class you should be able to sort your arrays numerically like this:
Arrays.sort(myarray, new AlphanumComparator());

U can use sol-1 if it contains only numbers in string format.
Solution-1: -
String []arr = {"3","2","4","10","11","6","5","8","9","7"};
Set<Integer> set = new TreeSet<Integer>();
Arrays.sort(arr);
for(String s:arr){
System.out.print(s+" ");
set.add(Integer.parseInt(s));
}
System.out.println(set);
Integer i = new Integer("4f");
System.out.println(i);
Solution-2:-
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Set<Integer> intSet = new TreeSet<Integer>();
Set<String> strSet = new TreeSet<String>();
Arrays.sort(arr);
for(String s:arr){
try {
int i = Integer.parseInt(s);
intSet.add(i);
} catch (NumberFormatException e) {
strSet.add(s);
}
}
List<String> result = new ArrayList<String>();
for(int val:intSet){
result.add(val+"");
}
result.addAll(strSet);
System.out.println(result);
}
Solution-3:-
Write one CustomComparator class and pass it to the sort() method.
public class CustomComparator implements Comparator<String>{
#Override
public int compare(String s1, String s2) {
Integer i1=null;
Integer i2=null;
try {
i1 = Integer.parseInt(s1);
} catch (NumberFormatException e) {
}
try {
i2 = Integer.parseInt(s2);
} catch (NumberFormatException e) {
}
if(i1!=null && i2!=null){
return i1.compareTo(i2);
}else{
return s1.compareTo(s2);
}
}
}
public static void main(){
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Arrays.sort(arr, new CustomComparator());
for(String s:arr){
System.out.print(s+" ");
}
}

If all elements if your String array represent numbers, and if the numbers are always positive, then there is a simple way to sort numerically without a limit to the value of the number.
This is based on the fact that a number with a larger number of digits is, in that case, always higher than a number with a smaller number of digits.
You first compare the number of digits, and then (only if the number of digits is the same) you compare the value alphabetically:
Arrays.sort(array,
Comparator.comparing(String::length).thenComparing(Function.identity()));

in jdk8, you can write this code with lambda.
List<String> list = Arrays.asList("3", "2", "4", "10", "11", "6", "5", "8", "9", "7");
list.sort(Comparator.comparingInt(Integer::valueOf));
list.forEach(System.out::println);
especially such as input
String[]{"3.b", "2.c", "4.d", "10.u", "11.a", "6.p", "5.i", "8.t", "9.e", "7.i"}
you can use string.subString to chose which value is you really want to sort.
like
files.sort(Comparator.comparingInt(a -> Integer.valueOf(a.substring(0, a.indexOf(".")))));

Your desired output contains the numerical order of corresponding integers of your strings. So simply you cannot avoid conversion of strings to integers. As an alternative comparator to vikingsteve's you can use this:
Arrays.sort(array, new Comparator<String>() {
#Override
public int compare(String str1, String str2) {
return Integer.parseInt(str1) - Integer.parseInt(str2);
}
});

public class test1 {
public static void main(String[] args)
{
String[] str = {"3","2","4","10","11","6","5","8","9","7"};
int[] a = new int[str.length];
for(int i=0;i<a.length;i++)
{
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
str[i]=String.valueOf(a[i]);
}
}
}

This is the best solution I could come with, we can't convert to integer when the string is huge, this method sort an array of strings
public static void sortListOfStringsAsNumbers(List<String> unsorted) {
String min = "";
for (int i = 0; i < unsorted.size(); i++){
min = unsorted.get(i);
int indexMin = i;
for (int j = i + 1; j < unsorted.size(); j++){
if (unsorted.get(j).length() < min.length()){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).length() == min.length()){
for (int x = 0; x < unsorted.get(j).length(); x ++){
if (unsorted.get(j).charAt(x) < min.charAt(x)){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).charAt(x) > min.charAt(x)){
break;
}
}
}
}
if (indexMin != i){
String temp = unsorted.get(i);
unsorted.set(i, min);
unsorted.set(indexMin, temp);
}
}
}

All the solutions are for only integer numbers. what if the array contains floating numbers as well?
Here is the best solution which allows you to sort any type of value in the string.
import java.math.BigDecimal;
import java.util.*;
class Sort
{
public static void main(String...arg)
{
String s[]={"-100","50","0","56.6","90","0.12",".12","02.34","000.000"};
System.out.println("\n"+Arrays.toString(s)); //print before sorting
Arrays.sort(s, new Comparator<String>() {
public int compare(String a1, String a2) {
BigDecimal a = new BigDecimal(a1);
BigDecimal b = new BigDecimal(a2);
return a.compareTo(b);
}
});
System.out.println("\n"+Arrays.toString(s)); //print after sorting
}
}

Related

Sort an ArrayList by first word

So, I have read a hashtable into a ArrayList for sorting purposes.
I have a lot of numeric values followed by whitespace and then another number which indicates where it was found from a text file. So my unsorted Array looks something like this:
10 1
11 7
1 12
47 9
and so on.
If i sort this by Collection.sort(); my array will look like this:
10 1
1 7
11 12
47 9
So it compares them alphabetically, not numerically. What I want is to ignore the second number and sort the list by the first word.
public void xor(arrayObject[] array){
try{
FileWriter textWriter = new FileWriter(new File("xor.txt"));
ArrayList<String> temp = new ArrayList<>();
String tempString;
for(int i = 0; i < array.length; i++){
if(array[i] != null){
tempString ="";
int hash = hashFunction(i);
int length = String.valueOf(array[hash].value).length();
if(array[hash].foundFromA && !array[hash].foundFromB){
tempString += Integer.toString(array[hash].value);
for(int a = 0; a < 10-length; a++){
tempString += " ";
}
tempString += "1";
temp.add(tempString);
}
else if(!array[hash].foundFromA && array[hash].foundFromB){
tempString += Integer.toString(array[hash].value);
for(int a = 0; a < 10-length; a++){
tempString += " ";
}
tempString += "2";
temp.add(tempString);
}
}
}
Collections.sort(temp);
for(String s : temp){
textWriter.write(s);
textWriter.write(System.lineSeparator());
}
textWriter.close();
System.out.println("Writing xor file succesful");
}
catch(IOException e){
System.out.println("Failed to save file");
}
}
you can make a comparator class and use it in the sort method
public class MyComparator implements java.util.Comparator<String> {
public int compare(String s1, String s2) {
return Integer.parseInt(s1.split( " " )[0]) - Integer.parseInt( s2.split( " " )[0] );
}
}
use it like this
Collections.sort(temp, new myComparator());
As stated by Abdou you can use a Comparator, but you can pass it directly to the sort method instead of create a separate class, which is easier imho.
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>();
myList.add("10 1");
myList.add("11 7");
myList.add("1 12");
myList.add("47 9");
myList.add("110 9");
Collections.sort(myList, new Comparator<String>() {
public int compare(String a, String b) {
int n1 = Integer.parseInt(a.split(" ")[0]);
int n2 = Integer.parseInt(b.split(" ")[0]);
return n1 - n2;
}
});
for (String item : myList) {
System.out.println(item);
}
}
}
Although I'd create a class for the values and let this class implement the Comparable interface. It would be cleaner and the sort method would work out of the box.

Comparator<String> returns appropriate values, but ArrayList is not Sorted

I'm trying to sort an ArrayList of Strings using a custom Comparator, called in the Collections.sort() method.
The code is
public static String largestNumber(final List<Integer> a) {
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<a.size(); i++) {
list.add(String.valueOf(a.get(i)));
}
Comparator<String> c = new Comparator<String>() {
public int compare(String s1, String s2) {
System.out.println("comparing: "+(s1+s2)+
" and "+(s2+s1));
System.out.println((s1+s2).compareTo(s2+s1));
return (s1+s2).compareTo(s2+s1);
}
};
for(int i=0; i<a.size(); i++) {
Collections.sort(list, c);
System.out.println("sorted:");
for(int j=0; j<a.size(); j++) {
System.out.print(list.get(j));
}
System.out.println();
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<list.size(); i++) {
sb.append(list.get(i));
}
return sb.toString();
}
The comparator returns the appropriate values. For example, when it is comparing string "303" and "330", it returns a negative value. However, the ArrayList remains unmodified. What's going on?
If you are comparing numbers, just parse them into Integer and then subtract them. The Collection will do the rest.
The Comparator Interface is just a contract that states for two elements being compared, if the value of A is minor than the value of B (AB), then A comes firsts. If the value of A is equal than the value of B (A==B), then it's likely that the Collection implementation places them together arbitrarily.
You just need to do the following:
Comparator<String> c = new Comparator<String>() {
public int compare(String s1, String s2) {
System.out.println("comparing: "+ s1 +
" and " +s2);
//Avoid the below check, it creates an infinite recursion.
//System.out.println(s1.compareTo(s2));
//Since you Strings are number, it's ok to do this.
int a = Integer.parseInt( s1 ); //Auto-unboxing;
int b = Integer.parseInt( s2 ); //Auto-unboxing;
return a-b;
}
};
Also, avoid recursion of comparations, it creates an infinite recursion, in which leads to an StackOverFlowException exception.
I hope I have helped.
Have a nice day. :)
Figured out what the problem was. I needed to return (s2+s1).compareTo(s1+s2);

Getting data from a given String separated by (,,-) in java

I am having a String like this "5006,3030,8080-8083".
I want each element separately from the String:
5006
3030
8080
8081
8082
8083
Here's my code:
int i=0,j=0;
String delim = "[,]";
String hyphon = "[-]";
String example = "5006,3030,8080-8083";
String p[] = example.split(delim);
int len = p.length;
for(i=0;i<len;i++) {
String ps[]=p[i].split(hyphon);
if(ps.length>1) {
int start = Integer.parseInt(ps[0]);
int finish = Integer.parseInt(ps[1]);
int diff = finish-start+1;
for(j=0;j<diff;j++) {
System.out.println(start+j);
}
} else if(ps.length==1) {
System.out.println(ps[0]);
}
}
Is there any better solution or any class that simplifies my code?
I also want the numbers in a ascending order.
Try this code :
public static void main(String[] args) {
String input = "5006,3030,8080-8083";
List<Integer> list = new ArrayList<Integer>();
String[] numbers = input.split(",");
for (String s : numbers) {
if (s.contains("-")) {
String[] range = s.split("-");
int from = Integer.parseInt(range[0]);
int to = Integer.parseInt(range[1]);
for (int i = from; i <= to; i++) {
list.add(i);
}
}
else {
list.add(Integer.parseInt(s));
}
}
System.out.println("in asc order");
Collections.sort(list);
System.out.println(list.toString());
System.out.println("in desc order");
Collections.reverse(list);
System.out.println(list.toString());
}
My output :
in asc order
[3030, 5006, 8080, 8081, 8082, 8083]
in desc order
[8083, 8082, 8081, 8080, 5006, 3030]
I also want the numbers in a ascending order.
This adds an unexpected twist to your whole program, because once you realize that printing-as-you-go no longer works, you need to start almost from scratch.
The first thing to do is picking an appropriate representation. It appears that you represent ranges of integers, so start by defining a class for them:
class IntRange : Comparable<IntRange> {
private int low, high;
public int getLow() {return low;}
public int getHigh() {return high;}
public IntRange(int low, int high) {
// Add range check to see if low <= high
this.low = low; this.high = high;
}
public IntRange(int point) {low = high = point;}
#Override
public void print() {
for (int i = low ; i <= high ; i++) {
System.out.println(i);
}
}
#Override
public int compareTo(IntRange other) {
...
}
}
Now you can use your code to split on [,], then split on [-], construct IntRange, and put it into an ArrayList<IntRange>. After that you can use sort() method to sort the ranges, and print them in the desired order.
But wait, there is more to your problem than meets the eye. Think what would happen for input like this:
1,5,3-7,6
Where should 5 and 6 be printed? It is not good to print it before or after 3-7, so the trick is to remove points inside ranges.
But even that's not all: what do you do about this input?
1-5,3-7
You should print numbers 1 through 7, inclusive, but this would require merging two ranges. There is a good data structure for doing this efficiently. It is called a range tree. If your input is expected to be large, you should consider using range tree representation.
You are good to go; you can minimize the counter variables using enhanced for loop and while loop.
String example = "5006,3030,8080-8083";
String[] parts=example.split(",")
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(String part: parts)
{
if(part.contains("-"))
{
String subParts[]=part.split("-");
int start = Integer.parseInt(subParts[0]);
int finish = Integer.parseInt(subParts[1]);
while(start <= finish)
{
numbers.add(start);
System.out.println(start++);
}
}
else {
System.out.println(part);
numbers.add(Integer.parseInt(part));
}
}
Integer[] sortedNumbers = new Integer[numbers.size()];
sortedNumbers = Arrays.sort(numbers.toArray(sortedNumbers));
Update (from comment):
Numbers are sorted now.
Try this
String str = "5006,3030,8080-8083";
String[] array = str.split(",");
String ans = "";
for(int i = 0; i < array.length; i++){
if(array[i].contains("-")){
String[] array2 = array[i].split("-");
int start = Integer.parseInt(array2[0]);
int end = Integer.parseInt(array2[array2.length - 1]);
for(int j = start; j <= end; j++){
ans = ans + j + ",";
}
}
else{
ans = ans + array[i] + ",";
}
}
System.out.print(ans);
This code assumes all integers are positive.
public static void main(String[] args) {
String testValue="5006,3030,8080-8083";
Integer[]result=parseElements(testValue);
for (Integer i:result){
System.out.println(i);
}
}
/**
* NumberList is a string of comma-separated elements that are either integers, or a range of integers of the form a-b.
* #param numberList
* #return all the integers in the list, and in ranges in the list, in a sorted list
*/
private static Integer[] parseElements(String integerList) {
ArrayList<Integer> integers=new ArrayList<Integer>();
String[] csvs=integerList.split(",");
for(String csv : csvs){
if(csv.contains("-")){
String[] range=csv.split("-");
Integer left=Integer.decode(range[0]);
Integer right=Integer.decode(range[1]);
for(Integer i=left;i<=right;i++){
integers.add(i);
}
} else {
integers.add(Integer.decode(csv));
}
}
Collections.sort(integers);
return integers.toArray(new Integer[0]);
}
Using Guava's functional idioms you can achive this declaratively, avoiding the verbose, imperative for-loops. First declare a tokenizing function which converts each token in the comma-delimited string into an Iterable<Integer>:
private static final Function<String, Iterable<Integer>> TOKENIZER =
new Function<String, Iterable<Integer>>() {
/**
* Converts each token (e.g. "5006" or "8060-8083") in the input string
* into an Iterable<Integer>; either a ContiguousSet or a List with a
* single element
*/
#Override
public Iterable<Integer> apply(String token) {
if (token.contains("-")) {
String[] range = token.trim().split("-");
return ContiguousSet.create(
Range.closed(Integer.parseInt(range[0]),
Integer.parseInt(range[1])),
DiscreteDomain.integers());
} else {
return Arrays.asList(Integer.parseInt(token.trim()));
}
}
};
then apply the function to the input:
String input = "5006,3030,8080-8083";
Iterable<String> tokens = Splitter.on(',').trimResults().split(input);
SortedSet<Integer> numbers = Sets.newTreeSet();
Iterables.addAll(numbers,
// concat flattens the Iterable<Iterable<Integer>>
// into an Iterable<Integer>
Iterables.concat(Iterables.transform(tokens, TOKENIZER)));
As all of the logic is basically coded into the Function, the client code only needs to tokenize the string into an Iterable<String> (with Splitter), apply the Function through Iterables.transform, flatten the result of the transformation using Iterables.concat and finally add the resulting Iterable<Integer> into a SortedSet<Integer> which keeps the numbers in ascending order.
with java 8 stream api :
public static void main(String[] args) {
String s = "5006,3030,8080-8083";
Arrays.stream(s.split(","))
.flatMap(el -> el.contains("-") ? rangeToStream(el) : Stream.of(Integer.valueOf(el)))
.sorted()
.forEachOrdered(e -> System.out.println(e));
}
private static Stream<? extends Integer> rangeToStream(String el) {
AtomicInteger[] bounds = Arrays.stream(el.split("-")).map(e -> new AtomicInteger(Integer.parseInt(e))).toArray(size -> new AtomicInteger[2]);
return Arrays.stream(new Integer[bounds[1].get() - bounds[0].get() + 1]).map(e -> bounds[0].getAndIncrement());
}
U can code something like this -
String s="5006,3030,8080-8083";
String s2[]=s.split(",");
List<Integer> li= new ArrayList<Integer>();
List<Integer> numbers= new ArrayList<Integer>();
for(int i=0;i<s2.length;i++){
if(s2[i].contains("-")){
li.add(i);
}
else{
numbers.add(Integer.parseInt(s2[i]));
}
}
for(Integer i:li){
String str=s2[i];
String strArr[]=str.split("-");
for(int j=Integer.parseInt(strArr[0]);j<=Integer.parseInt(strArr[1]);j++){
numbers.add(j);
}
}
Collections.sort(numbers);
for(Integer k:numbers){
System.out.println(k);
}
public static void main(String[] args)
{
String example = "5006,3030,8080-8083";
String[] splitString = example.split(",");
List<Integer> soretedNumbers = new ArrayList<>();
for(String str : splitString)
{
String[] split2 = str.split("-");
if(split2.length == 1)
{
soretedNumbers.add(Integer.parseInt(str));
}
else
{
int num1 = Integer.parseInt(split2[0]);
int num2 = Integer.parseInt(split2[1]);
for(int i = num1;i <= num2; i++)
{
soretedNumbers.add(i);
}
}
}
Collections.sort(soretedNumbers);
for(int i : soretedNumbers)
{
System.out.println(i);
}
}

Sort a String array, whose strings represent int

I have String[] array like
{"3","2","4","10","11","6","5","8","9","7"}
I want to sort it in numerical order, not in alphabetical order.
If I use
Arrays.sort(myarray);
I obtain
{"10","11","2","3","4","5","6","7","8","9"}
instead of
{"2","3","4","5","6","7","8","9","10","11"}
Try a custom Comparator, like this:
Arrays.sort(myarray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
Hope you like it!
I think by far the easiest and most efficient way it to convert the Strings to ints:
int[] myIntArray = new int[myarray.length];
for (int i = 0; i < myarray.length; i++) {
myIntArray[i] = Integer.parseInt(myarray[i]);
}
And then sort the integer array. If you really need to, you can always convert back afterwards:
for (int i = 0; i < myIntArray.length; i++) {
myarray[i] = "" + myIntArray[i];
}
An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.
I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:
The Alphanum Algorithm
There is a Java implementation example linked from the article.
With that class you should be able to sort your arrays numerically like this:
Arrays.sort(myarray, new AlphanumComparator());
U can use sol-1 if it contains only numbers in string format.
Solution-1: -
String []arr = {"3","2","4","10","11","6","5","8","9","7"};
Set<Integer> set = new TreeSet<Integer>();
Arrays.sort(arr);
for(String s:arr){
System.out.print(s+" ");
set.add(Integer.parseInt(s));
}
System.out.println(set);
Integer i = new Integer("4f");
System.out.println(i);
Solution-2:-
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Set<Integer> intSet = new TreeSet<Integer>();
Set<String> strSet = new TreeSet<String>();
Arrays.sort(arr);
for(String s:arr){
try {
int i = Integer.parseInt(s);
intSet.add(i);
} catch (NumberFormatException e) {
strSet.add(s);
}
}
List<String> result = new ArrayList<String>();
for(int val:intSet){
result.add(val+"");
}
result.addAll(strSet);
System.out.println(result);
}
Solution-3:-
Write one CustomComparator class and pass it to the sort() method.
public class CustomComparator implements Comparator<String>{
#Override
public int compare(String s1, String s2) {
Integer i1=null;
Integer i2=null;
try {
i1 = Integer.parseInt(s1);
} catch (NumberFormatException e) {
}
try {
i2 = Integer.parseInt(s2);
} catch (NumberFormatException e) {
}
if(i1!=null && i2!=null){
return i1.compareTo(i2);
}else{
return s1.compareTo(s2);
}
}
}
public static void main(){
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Arrays.sort(arr, new CustomComparator());
for(String s:arr){
System.out.print(s+" ");
}
}
If all elements if your String array represent numbers, and if the numbers are always positive, then there is a simple way to sort numerically without a limit to the value of the number.
This is based on the fact that a number with a larger number of digits is, in that case, always higher than a number with a smaller number of digits.
You first compare the number of digits, and then (only if the number of digits is the same) you compare the value alphabetically:
Arrays.sort(array,
Comparator.comparing(String::length).thenComparing(Function.identity()));
in jdk8, you can write this code with lambda.
List<String> list = Arrays.asList("3", "2", "4", "10", "11", "6", "5", "8", "9", "7");
list.sort(Comparator.comparingInt(Integer::valueOf));
list.forEach(System.out::println);
especially such as input
String[]{"3.b", "2.c", "4.d", "10.u", "11.a", "6.p", "5.i", "8.t", "9.e", "7.i"}
you can use string.subString to chose which value is you really want to sort.
like
files.sort(Comparator.comparingInt(a -> Integer.valueOf(a.substring(0, a.indexOf(".")))));
Your desired output contains the numerical order of corresponding integers of your strings. So simply you cannot avoid conversion of strings to integers. As an alternative comparator to vikingsteve's you can use this:
Arrays.sort(array, new Comparator<String>() {
#Override
public int compare(String str1, String str2) {
return Integer.parseInt(str1) - Integer.parseInt(str2);
}
});
public class test1 {
public static void main(String[] args)
{
String[] str = {"3","2","4","10","11","6","5","8","9","7"};
int[] a = new int[str.length];
for(int i=0;i<a.length;i++)
{
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
str[i]=String.valueOf(a[i]);
}
}
}
This is the best solution I could come with, we can't convert to integer when the string is huge, this method sort an array of strings
public static void sortListOfStringsAsNumbers(List<String> unsorted) {
String min = "";
for (int i = 0; i < unsorted.size(); i++){
min = unsorted.get(i);
int indexMin = i;
for (int j = i + 1; j < unsorted.size(); j++){
if (unsorted.get(j).length() < min.length()){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).length() == min.length()){
for (int x = 0; x < unsorted.get(j).length(); x ++){
if (unsorted.get(j).charAt(x) < min.charAt(x)){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).charAt(x) > min.charAt(x)){
break;
}
}
}
}
if (indexMin != i){
String temp = unsorted.get(i);
unsorted.set(i, min);
unsorted.set(indexMin, temp);
}
}
}
All the solutions are for only integer numbers. what if the array contains floating numbers as well?
Here is the best solution which allows you to sort any type of value in the string.
import java.math.BigDecimal;
import java.util.*;
class Sort
{
public static void main(String...arg)
{
String s[]={"-100","50","0","56.6","90","0.12",".12","02.34","000.000"};
System.out.println("\n"+Arrays.toString(s)); //print before sorting
Arrays.sort(s, new Comparator<String>() {
public int compare(String a1, String a2) {
BigDecimal a = new BigDecimal(a1);
BigDecimal b = new BigDecimal(a2);
return a.compareTo(b);
}
});
System.out.println("\n"+Arrays.toString(s)); //print after sorting
}
}

Sorting String[][] unexpected output

I want to sort my String[][] with respect to second column. I tried this
public static String[][] sorting_minn(String[][] list){
double[] temp = new double[list.length];
String[][] tempf = list;
if(list[1][1]!=null){
for(int i = 0; i<list.length; i++){
if(list[i][2]==null){
break;
} else {
temp[i]=Double.parseDouble(list[i][2]);
}
}
Arrays.sort(temp);
for(int f = 0; f<list.length-1;f++){
for(int m = 0; m<list.length;m++){
if(list[m][2]!=null && Double.parseDouble(list[m][2])==temp[f]){
for(int n = 0; n<4; n++){
tempf[list.length-f-1][n]=list[m][n];
}
m = list.length;
}
}
}
}
return tempf;
}
As an output I get this: . I need suggestion on how to improve this code.
try something like:
Arrays.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
String left = o1[1]!=null ? o1[1] : "";
String right = o2[1]!=null ? o2[1] : "";
return left.compareTo(right);
}
});
this treats nulls as empty strings, and exploits the fact that strings are comparable, although lexicographic. if you want the reverse order just do this instead:
right.compareTo(left)
if you want integer ordering you could parse an Integer out of both sides (Integer.MIN for null) and compare 2 Integers

Categories