Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 根据优先级值进行筛选的最佳方法_Java_Java Stream - Fatal编程技术网

Java 根据优先级值进行筛选的最佳方法

Java 根据优先级值进行筛选的最佳方法,java,java-stream,Java,Java Stream,在集合(Iterable)中,如果存在重复项,我希望筛选优先级值 类的数据表示可以如下所示: [ { "uuid": "56a00526-871f-43d4-86fe-0df1773f5cdf", "entry": "CASSIER", "rate": { "uuid": "0b264f4d-3f3f-4e39-3f3f-3f53263f303d", "type": 2, "rate": 430 } }, {

在集合(Iterable)中,如果存在重复项,我希望筛选优先级值

类的数据表示可以如下所示:

[
  {
    "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):


是否存在Java流?

最后,我使用谓词筛选了一个Iterable,并在按速率对Iterable排序后筛选了一个流筛选器。类型:

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());

public static Predicate distinctByKey(函数)您使用的是哪种类型的集合?如果您使用的是标准集合,则可以使用Collections.sort来实现所需的功能。@SanjitKumarMishra我使用的是Iterable
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());