在未知值之前对具有已知值的列表进行排序 [英] Sort a list with known values before unknown values

查看:58
本文介绍了在未知值之前对具有已知值的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下规则对列表进行排序:

I'm trying to sort a list with the following rules:

  1. 已知值应该在未知值之前排序.
  2. 已知值应通过单独定义的键排序.
  3. 未知值应按其自然顺序进行排序.

我有(1)和(2),只是想在混合中添加(3).

I've got (1) and (2), just struggling with adding (3) in to the mix.

到目前为止,我有这个:

So far I have this:

List<String> values = Arrays.asList(
    "red", "orange", "yellow", "green", "blue", "indigo", "violet");

ImmutableMap<String, Integer> map = ImmutableMap.of("red", 1, "green", 2, "blue", 3);

Ordering<String> order = Ordering.natural()
    .nullsLast()
    .onResultOf(Functions.forMap(map, null));

Collections.sort(values, order);

System.out.println(values);

哪个会产生:

[red, green, blue, orange, yellow, indigo, violet]

但最后4个按其原始顺序排列,而我希望它们按其自然顺序排序:

But the last 4 are in their original order, whereas I'd like them sorted in their natural order:

[red, green, blue, indigo, orange, violet, yellow]

我唯一想到的就是编写自己的自定义函数,该函数在地图中查找内容并将地图结果添加到原始值,如果找不到地图则使用地图大小-例如它会返回:

The only thing I can think of is writing my own custom function, which looks things up in the map and prepends the map result to the original value, using the map size if not found - e.g. it would return:

"1-red", "4-orange", "4-yellow", "2-green", "3-blue", "4-indigo", "4-violet"

但这仅在映射值是整数并且要求数字格式将"02"排序为"10"等之前有效.

But that only works if the mapped values are integers, and requires number formatting to order "02" before "10" etc.

任何人都有更好的方法来实现这一目标吗?

Anyone have a better way of achieving this?

推荐答案

这是Guava版本(当您使用Java 7或更低版​​本时):

Here's the Guava version (when you're on Java 7 or lower):

Ordering<String> ordering = Ordering.natural().nullsLast()
        .onResultOf(Functions.forMap(map, null))
        .compound(Ordering.natural());

这是使用纯Comparator的非番石榴版本(在JDK 8+上):

Here's the non-Guava version using pure Comparator (when on JDK 8+):

Comparator<String> comparator = Comparator
        .<String, Integer>comparing(map::get, Comparator.nullsLast(Comparator.naturalOrder()))
        .thenComparing(Comparator.naturalOrder());

PS.如您所见,使用Guava API的类型推断更好(无需指定显式类型参数).

PS. As you can see, the type inference in case of the Guava API is better (no need to specify explicit type parameters).

这篇关于在未知值之前对具有已知值的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆