简体   繁体   中英

How to sort a string array in ascending order according to a particular unit?

String[] stringArray = {"1 kbps", "100 bps", "10 mbps", "2 gbps"};

the needed output

{ "100 bps","1 kbps", "10 mbps", "2 gbps"}

in ascending order

Use comparator like this:

 String[] stringArray = {"1 kbps", "100 bps", "10 mbps", "2 gbps"}; Arrays.sort(stringArray, new SpeedComparator()); System.out.println(Arrays.asList(stringArray)); // [100 bps, 1 kbps, 10 mbps, 2 gbps]
import java.util.Comparator;

public class SpeedComparator implements Comparator<String> {

  public int compare(String o1, String o2) {

    int indexSeparator1 = o1.indexOf(' ');
    int indexSeparator2 = o2.indexOf(' ');
    String number1 = o1.substring(0, indexSeparator1);
    String number2 = o2.substring(0, indexSeparator2);

    double value1 = Double.valueOf(number1);
    double value2 = Double.valueOf(number2);

    String measure1 = o1.substring(indexSeparator1 + 1, o1.length());
    String measure2 = o2.substring(indexSeparator2 + 1, o2.length());

    value1 = getRealValue(value1, measure1);
    value2 = getRealValue(value2, measure2);

    return (int) (value1 - value2);

  }

  private double getRealValue(double value, String measure) {
    switch (Measure.valueOf(measure.toUpperCase())) {
      case BPS:
        return value;
      case KBPS:
        return value * 1000;
      case MBPS:
        return value * 1000000;
      case GBPS:
        return value * 1000000000;
    }
    return value;
  }

  enum Measure {
    BPS, KBPS, MBPS, GBPS
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM