简体   繁体   中英

Sort numbers 1-10 stored as their spelling in a arraylist in java

I have arraylist of string as follows

List<String> list = new ArrayList<String>();
list.add("one");
list.add("ten");
list.add("six");
list.add("two");

output after sorting should be
one, two, six, ten

You can order based in values of a Map for example:

Map<String, Integer> numbers = new HashMap<>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
numbers.put("four", 4);
numbers.put("five", 5);
numbers.put("six", 6);
numbers.put("seven", 7);
numbers.put("height", 8);
numbers.put("nine", 9);
numbers.put("ten", 10);

List<String> list = new ArrayList<>();
list.add("one");
list.add("ten");
list.add("six");
list.add("two");

Collections.sort(list, (o1, o2) -> {
    return numbers.get(o1) - numbers.get(o2);
});
System.out.println(list);

Output

[one, two, six, ten]

Quick and short solution:

List<String> allNumbers = Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");
Collections.sort(list, (i1, i2) -> allNumbers.indexOf(i1) - allNumbers.indexOf(i2));

Use a HashMap with indexed string keys for a faster algorithm (if you have 10 values, there's no difference anyway).

Java doesn't provide an out of box way to sort String in this ways.
You could use a Comparator that compare the value of two String according to this rule.

An effective way would be to create in the Comparator class with all String that you want to sort and use the index of the element to know its order.

For example :

public class MyNumberInStringComparator implements Comparator<String> {

    private static List<String> numbers = Arrays.asList("one", "two", "three");             


    @Override
    public int compare(String o1, String o2) {
        return Integer.compare(numbers.indexOf(o1),numbers.indexOf(o2));
    }

}

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