We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n];
for(int i=0;i<n;i++){
s[i]=sc.next();
}
sc.close();
//My way of solving this problem
List<String> list = new ArrayList<String>();
Collections.addAll(list,s);
//reversing the ArrayList according to the BigDecimal values
list.sort((a,b)->{return -1* new BigDecimal(a).compareTo(new BigDecimal(b));});
s = list.toArray(new String[s.length]);// you can also put "new String[0]
for (String string : s) {
System.out.println(string);
}
System.out.println(">>>>>>>");
//Solution from hackerRank discussion
//This is way too efficient than my own way.
//I didn't know that an array can be sorted.
//And thus, I messed up.
//You can achieve this operation with lambda expression
//Again You can use Arrays.sort on Array, then define a lambda expression
//Just see my own way where I executed with lambda.
Arrays.sort(s, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return new BigDecimal(b).compareTo(new BigDecimal(a));
}
});
for (String string : s) {
System.out.println(string);
}
System.out.println(">>>>>>>");
//For the sake of completion
Arrays.sort(s,(a,b)->{return new BigDecimal(b).compareTo(new BigDecimal(a));});
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java BigDecimal
You are viewing a single comment's thread. Return to all comments →
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; import java.math.BigDecimal;
public class JavaBigDecimal {
}