Sort the list: learn to use Guava Ordering

introduction

Daily moving bricks, frequently the case, re-sort the various front-end returns a list of elements based on different strategies, so with this article, learn to use Orderiing the Guava .

Guava Ordering

Still, cited under the official definition:

Sequencer (Ordering) is smooth style comparator Guava [Comparator] implementation, which can be used to build complex comparator to complete the set of ordered functions.

API and basic use

In use, Orderingit provides support for chained calls, making the code becomes clear and concise.

  • In order to clearly understand Orderingthe operation to the Entitylist of objects of different sort (I did not use lazy Getterand Setterdirectly publicdeclare member variables.).
public class Entity {

    public int status;
    public String name;

    public Entity(int status, String name) {
        this.status = status;
        this.name = name;
    }

    public Entity(int status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Entity{" +
                "status=" + status +
                ", name='" + name + '\'' +
                '}';
    }
}
复制代码
  • Test Data
List<Entity> list = new ArrayList<Entity>() {{
            add(new Entity(1, "h"));
            add(new Entity(2, "f"));
            add(new Entity(3, "a"));
            add(new Entity(0, "d"));
            add(new Entity(2, "b"));
        }};
复制代码

Ordering initialization

Ordering initialization method there are three, respectively, for the different scenarios.

  • Sortable data type of the sorter
// 整型按照大小排序
Ordering<Integer> integerOrdering = Ordering.natural();
// 日期先后排序
Ordering<Date> dateOrdering = Ordering.natural();
复制代码
  • By a string dictionary object do the sorting [lexicographical ordering]
// 排序结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='b'}, Entity{status=2, name='f'}, Entity{status=3, name='a'}]

Ordering<Object> ordering3 = Ordering.usingToString();
复制代码
  • According to custom Comparatorinitialization
// 排序结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}, Entity{status=3, name='a'}]
// 按照status字段升序排序
Ordering<Entity> ordering1 = Ordering.from(Comparator.comparingInt(o -> o.status));
复制代码

Chained method calls

  • reverse()
// 倒序排序
// 排序结果:[Entity{status=3, name='a'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}, Entity{status=1, name='h'}, Entity{status=0, name='d'}]
Ordering<Object> ordering3 = Ordering.usingToString().reverse();
复制代码
  • nullsFirst (), nullsLast (): the value of the null routed front / rearmost position.

  • compound (Comparator secondaryComparator <super U?>): Synthesis of a further comparator, to handle the current situation is equal to the sequencer.

// status升序排序
Ordering<Entity> ordering1 = Ordering.from(Comparator.comparingInt(o -> o.status));
// status相等,按照name升序排序
// 排序结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='b'}, Entity{status=2, name='f'}, Entity{status=3, name='a'}]
Ordering<Entity> ordering4 = ordering1.compound((o1, o2) -> StringUtils.compare(o1.name, o2.name));
复制代码
  • onResultOf(Function<F, ? extends T> function)
// status升序 null的对象放在最后面
// 排序结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}, Entity{status=3, name='a'}, null]

Ordering<Entity> ordering = Ordering.natural().onResultOf(new Function<Entity, Comparable>() {
        @Override
        public Comparable apply(Entity entity) {
            if (entity != null) {
                return entity.status;
            }
            return -1;
        }
    }).nullsLast();
复制代码

Sequencer using methods

  • greatestOf(Iterable iterable, int k)/leastOf
// 排序结果:[null, Entity{status=3, name='a'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}]
// nullLast()导致null最大,最大的四个元素
ordering.greatestOf(list, 4)
// 排序结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}]
// 最小的四个元素
ordering.leastOf(list, 4)
复制代码
  • min(Iterable iterable)/max
// 结果:Entity{status=0, name='d'}
ordering.min(list)
// 还支持N个对象的比较
// 结果:Entity{status=1, name='y'}
ordering.min(new Entity(1, "y"), new Entity(2, "x"))
复制代码
  • sortedCopy (Iterable iterable) look at the source code to see what has been done?
public <E extends T> List<E> sortedCopy(Iterable<E> iterable) {
// 转换成了对象数组
        E[] array = (Object[])Iterables.toArray(iterable);
        // Ordering继承Comparator,使用Ordering排序
        Arrays.sort(array, this);
        // 最后复制到新建列表中
        return Lists.newArrayList(Arrays.asList(array));
    }
复制代码
  • We can see the source code, Orderingto sort the results as a new list of objects, no changes to the original list.
// 数据:
 List<Entity> list = new ArrayList<Entity>() {{
            add(new Entity(1, "h"));
            add(new Entity(2, "f"));
            add(new Entity(3, "a"));
            add(new Entity(0, "d"));
            add(new Entity(2, "b"));
            add(null);
        }};
// 结果:[Entity{status=0, name='d'}, Entity{status=1, name='h'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}, Entity{status=3, name='a'}, null]
[Entity{status=1, name='h'}, Entity{status=2, name='f'}, Entity{status=3, name='a'}, Entity{status=0, name='d'}, Entity{status=2, name='b'}, null]

System.out.println(ordering.sortedCopy(list));
        System.out.println(list);
复制代码

Combined with the strategy pattern: practice

Strategy Mode Introduction

  • Policy model object behavioral patterns, is the definition of a series of algorithms, these algorithms into a single package separate classes.
  • Under the policy reference pattern class diagram:
    Alt text

The Code

  • interface
public interface IEntityStrategy {

    List<Entity> sort(List<Entity> list);
}
复制代码
  • Strategy 1: Entity objects sorted in reverse order status
public class StatusDESCStrategy implements IEntityStrategy {

    private static Ordering<Entity> ordering = Ordering.natural().onResultOf(new Function<Entity, Comparable>() {
        @Override
        public Comparable apply(Entity entity) {
            if (entity != null) {
                return entity.status;
            }
            return -1;
        }
    }).nullsLast();

    @Override
    public List<Entity> sort(List<Entity> list) {
        return ordering.sortedCopy(list);
    }
}
复制代码
  • Strategy 2: Entity objects sorted by name in ascending order
public class NameASCStrategy implements IEntityStrategy {

    private static Ordering<Entity> ordering = Ordering.from((o1, o2) -> StringUtils.compare(o1.name, o2.name));

    @Override
    public List<Entity> sort(List<Entity> list) {
        return ordering.sortedCopy(list);
    }
}
复制代码
  • test
public class Test {

    public static void main(String[] args) {
        List<Entity> list = new ArrayList<Entity>() {{
            add(new Entity(1, "h"));
            add(new Entity(2, "f"));
            add(new Entity(3, "a"));
            add(new Entity(0, "d"));
            add(new Entity(2, "b"));
            add(null);
        }};

        Context context = new Context(new StatusDESCStrategy());
        System.out.println("status字段降序排序");
        // 结果:[Entity{status=3, name='a'}, Entity{status=2, name='f'}, Entity{status=2, name='b'}, Entity{status=1, name='h'}, Entity{status=0, name='d'}, null]
        System.out.println(context.sortByStrategy(list));
        // 结果:[Entity{status=3, name='a'}, Entity{status=2, name='b'}, Entity{status=0, name='d'}, Entity{status=2, name='f'}, Entity{status=1, name='h'}, null]
        Context context1 = new Context(new NameASCStrategy());
        System.out.println("name字段升序排序");
        System.out.println(context1.sortByStrategy(list));
    }
}
复制代码
  • Personal opinion: In order to reduce the actual object is created, the policy practice class can be created using the Singleton pattern and will not be Context, directly on the policy class treatment.

references

ifeve.com/google-guav... design patterns .pdf www.runoob.com/design-patt...

Guess you like

Origin juejin.im/post/5d3806956fb9a07eb74b7fb4