2017-08-25 56 views
0
匹配不同类型的对象

我有以下类别:由共同财产中的Java

abstract class Executor { 
String executorType; 

public Executor(String executorType) {this.executorType = executorType;} 

public void execute(String dataContent); 
} 

class Data { 
String dataType; 
String dataContent; 
} 

鉴于数据单项的名单,和执行者的名单(具体那些延长执行人),我想每一个执行程序只会调用与其类型相同类型的数据执行。换句话说,只有在executor.executorType == data.dataType

执行程序将执行数据时,我该如何使用Java 8提供的流,收集器和其他东西很快并具有良好性能?

这里,我已经做出了表率,但我想我可以做的更好:

(注: 1.在我的例子,我创建执行者和数据之间的地图上,他们可以运行自己的执行()方法,但如果有一个解决方案跳过地图创建并立即运行execute(),那就更好了 2.在我的例子中,我假定Executor是一个具体的类,不是抽象的,只是为了方便起见

List<Executor> executorList = Arrays.asList(new Executor("one"), new Executor("two"), new Executor("three")); 
List<Data> dataList = Arrays.asList(new Data("one","somecontent"), new Data("two","someOtherContent"), new Data("one","longContent")); 
Map<List<Executor>, List<Data>> stringToCount = dataList.stream().collect(
      Collectors.groupingBy(t-> executorList.stream().filter(n -> n.executorType.equals(t.getName())).collect(Collectors.toList()))); 

回答

0

我该怎么做,很快,并与去od性能,使用由Java 8提供的流,收集器和其他东西?

那么你的目标是什么?良好的性能或使用Java 8 Streams?

随着流会是这样的:沿线

dataList 
    .forEach(data -> executorList 
     .stream() 
     .filter(executor -> Objects.equals(data.dataType, executor.executorType)) 
     .findAny() 
     .map(executor -> executor.execute(data.dataContent))); 

不知道有关语法,但一些。

但我实际上首先制作Map<String, Executor>Executor.executorType然后就是executors.get(data.dataType)。你也可以实现一个VoidExecutor它什么也不做,并呼吁

executors.getOrDefault(data.dataType, VoidExecutor.INSTANCE).execute(data.dataContent); 

具有哈希映射您可能希望含量的不同时间的查找。

+0

我的目标是让它以最佳的时间复杂度运行并且写得优雅,但是我认为如果不使用流,它不会更好。当然我错了。关于地图,这是我想用的东西,但我仍然希望避免它。 – ibri