Distinct() 在 Stream 上使用时似乎不会过滤掉相同的结果

Posted

技术标签:

【中文标题】Distinct() 在 Stream 上使用时似乎不会过滤掉相同的结果【英文标题】:Distinct() doesn't seem to filter out identical results when used on a Stream 【发布时间】:2020-12-13 05:17:31 【问题描述】:

请看一下这段代码 =>

void main() async 
  Stream<int> _intStream() async* 
    for (int i = 0; i < 10; i++) yield i;
  

  Stream<int> _even() => _intStream().where((int i) => i % 2 == 0);
  Stream<bool> _isEven(Stream<int> stream) => stream.map((int i) => i % 2 == 0);

  print('test 1: should print 5 [true] and 5 [false] alternate');
  await for (bool b in _isEven(_intStream())) 
    print('test 1: $b');
  

  print('test 2: should print 5 [true]');
  await for (bool b in _isEven(_even())) 
    print('test 2: $b');
  

  print('test 3: should print ONLY ONE [true]');
  await for (bool b in _isEven(_even().distinct())) 
    print('test 3: $b');
  

我是不是用错了distinct()

提前谢谢你

【问题讨论】:

【参考方案1】:

没关系,我只是把 distinct 放在错误的地方, 以下按预期工作

void main() async 
  Stream<int> _intStream() async* 
    for (int i = 0; i < 10; i++) yield i;
  

  Stream<int> _even() => _intStream().where((int i) => i % 2 == 0);
  Stream<bool> _isEven(Stream<int> stream) => stream.map((int i) => i % 2 == 0);

  print('test 1: should print 5 [true] and 5 [false] alternate');
  await for (bool b in _isEven(_intStream())) 
    print('test 1: $b');
  

  print('test 2: should print 5 [true]');
  await for (bool b in _isEven(_even())) 
    print('test 2: $b');
  

  print('test 3: should print ONLY ONE [true]');
  await for (bool b in _isEven(_even()).distinct()) 
    print('test 3: $b');
  

【讨论】:

以上是关于Distinct() 在 Stream 上使用时似乎不会过滤掉相同的结果的主要内容,如果未能解决你的问题,请参考以下文章

java8 stream limit distinct map flatMap

任意键上的Java Lambda Stream Distinct()? [复制]

list去重+Java8-Stream distinct 根据list某个字段去重

Java Stream 流的使用

分享几种 Java8 中通过 Stream 对列表进行去重的方法

java stream Api