2

I'm having 3 values like

a^100,b^200,c^150

I need to sort these values in the order of

b^200,c^150,a^100

How can i do this in java?

4
  • From your example I don't understand how the values are meant to be sorted. Could you describe the sorting rule? Commented Mar 23, 2011 at 9:51
  • Are you asking how to perform a sort using Java or for an algorithm to compare "a^100" and "b^200" correctly? Commented Mar 23, 2011 at 9:52
  • get the integer after ^ like 100,200,150.compare those values,sort and give the results as 200,150,100. Commented Mar 23, 2011 at 9:54
  • All i need is after giving input as a^100,b^200,c^150 the result should be like this:"b should come first,follows by c finally a.Sort based on the value that was given after ^. Commented Mar 23, 2011 at 9:59

2 Answers 2

3

Use a custom Comparator, like this one:

public class IntegerSubstringCompare implements Comparator<String> {
    @Override
    public int compare(String left, String right) {
        Integer leftInt = Integer.parseInt(left.substring(left.indexOf("^") + 1));
        Integer rightInt = Integer.parseInt(right.substring(right.indexOf("^") + 1));

        return -1 * leftInt.compareTo(rightInt);
    }
}

You can use it like this:

public static void main(String[] args) {
    String[] input = {"a^100", "b^200", "c^150"};
    List<String> inputList = Arrays.asList(input);
    Collections.sort(inputList, new IntegerSubstringCompare());
    System.out.println(inputList);
}
Sign up to request clarification or add additional context in comments.

Comments

0
String sample = "a^100,b^200,c^150";
List data = Arrays.asList(sample.split(","));
Collections.sort(data, Collections.reverseOrder( new Comparator<String>() {
public int compare (String obj1,String obj2)
{
  String num1 = obj1.split("\\^")[1];
  String num2 = obj2.split("\\^")[1];
  return  num1.compareTo(num2);
}
}));
String sortedSample[]= (String[])data.toArray(new String[data.size()]);
for (int z=0; z< sortedSample.length;z++ )
System.out.println(sortedSample[z]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.