【问题标题】:Best ways to filter on priority value过滤优先级值的最佳方法
【发布时间】:2016-06-21 09:18:34
【问题描述】:

在一个集合(可迭代)中,如果有重复,我想过滤优先级值。

类的数据表示可以是:

[
  {
    "uuid": "56a00526-871f-43d4-86fe-0df1773f5cdf",
    "entry": "CASSIER",
    "rate": {
      "uuid": "0b264f4d-3f3f-4e39-3f3f-3f53263f303d",
      "type": 2,
      "rate": 430
    }
  },
  {
    "uuid": "663f5d3f-3f3f-48da-a743-3f7b3f753e65",
    "entry": "CASTET",
    "rate": {
      "uuid": "3fdf9f2c-3f3f-4e3f-3f3f-263fe29d8d07",
      "type": 1,
      "rate": 13
    }
  },
  {
    "uuid": "8eae8c39-d667-4cc5-9b91-544454961399",
    "entry": "CASTET",
    "rate": {
      "uuid": "133f0315-413f-493f-3f24-3f3f6d3f5874",
      "type": 2,
      "rate": 345
    }
  },
  {
    "uuid": "6D680178-9B05-4744-A004-163D4B3E1E84",
    "entry": "JOHN",
    "rate": {
      "uuid": "EE877ABD-932F-4B4C-AB23-B324363B0B60",
      "type": 1,
      "rate": 13
    }
  }
]

异常结果(优先级:rate.type = 2):

[
  {
    "uuid": "56a00526-871f-43d4-86fe-0df1773f5cdf",
    "entry": "CASSIER",
    "rate": {
      "uuid": "0b264f4d-3f3f-4e39-3f3f-3f53263f303d",
      "type": 2,
      "rate": 430
    }
  },
  {
    "uuid": "8eae8c39-d667-4cc5-9b91-544454961399",
    "entry": "CASTET",
    "rate": {
      "uuid": "133f0315-413f-493f-3f24-3f3f6d3f5874",
      "type": 2,
      "rate": 345
    }
  },
  {
    "uuid": "6D680178-9B05-4744-A004-163D4B3E1E84",
    "entry": "JOHN",
    "rate": {
      "uuid": "EE877ABD-932F-4B4C-AB23-B324363B0B60",
      "type": 1,
      "rate": 13
    }
  }
]

用 Java Stream 做点什么?

【问题讨论】:

  • 您使用的是什么类型的集合?
  • 如果您使用的是标准集合,您可以使用 Collections.sort 来实现您想要的。
  • @SanjitKumarMishra 我正在使用 Iterable

标签: java java-stream


【解决方案1】:

最后,在按 rate.type 对 Iterable 进行排序后,我使用 Predicate 来过滤 Iterable 和 Stream 过滤器:

public static <T> Predicate<T> distinctByKey(Function<? super T,Object> keyExtractor) {
    Map<Object,Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

Stream s = StreamSupport.stream(registrations.spliterator(), false);
s.filter(distinctByKey((Registration r) -> r.getEntry().getUuid())).collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2019-04-15
    • 2020-03-22
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多