akka 筛选自定义数据类型的源

ncgqoxb0  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(164)

我正在学习akka流,并试图使用我写的下面的代码过滤源代码:

import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class sd001 {

    private static final ActorSystem system = ActorSystem.create("akkassembly");
    private static List<RData> ls = new ArrayList();

    private static class RData {
        private String id;

        public RData(String id){
            this.id = id;
        }

        public List<Integer> getValues(){
            return Arrays.asList(1,2,3,4,5);
        }

        public String getId() {
            return this.id;
        }
    }

    final static List<RData> builderFunction() {
        try {
            ls.add(new RData("1"));
            ls.add(new RData("2"));
            ls.add(new RData("3"));
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ls;
    }

    private static double calculateAverage(List <Integer> marks) {
        return marks.stream()
                .mapToDouble(d -> d)
                .average()
                .orElse(0.0);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        final Source<List<RData>, NotUsed> source =
                Source.repeat(NotUsed.getInstance()).map(elem -> builderFunction());
        source.filter(x -> x.getId().equals("1"));

    }

}

实际上,这段代码只是尝试过滤List<RData>类型的数据结构,但source.filter(x -> x.getId().equals("1"));行会导致编译器错误:

Cannot resolve method 'getId' in 'List'

通过阅读过滤器的akka文件:https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/filter.html我应该能够过滤列表值?

ukqbszuj

ukqbszuj1#

使用mapConcat展平集合似乎可以给予所需的结果:

final Source<List<RData>, NotUsed> source =
                Source.repeat(NotUsed.getInstance()).map(elem -> builderFunction());
        source.mapConcat(i -> i)
                .filter(x -> x.getId().equals("1"))

相关问题