[*] Нагрузить партию данных из базы данных < /li>
Карту этих данных (
Код: Выделить всё
Object[]
[*] записать в файл
[*] Повторите, пока запрос не получит больше результатов < /li>
< /ol>
Я перечислил структуры, с которыми я знаком, кажется, соответствует потребностям и почему они не соответствуют моим потребностям. < /p>
- Итератор → нет возможности для картирования и фильтра В подклассе, хотя и на самом деле не имея данных (аналогично потоку), чтобы я мог передать путь «потоковой» в класс вызова и только там вызовет следующий , который затем вызывает все функции карты как Результат < /li>
< /ul>
< /li>
Stream → Все данные должны быть доступны перед отображением и фильтрацией < /li>
наблюдаемый → отправляет данные, как только они будут доступны. Мне нужно обработать его синхронизировать, хотя
Код: Выделить всё
// Disclaimer: "Something" is the structure I am not sure of now.
// Could be an Iterator or something else that fits (Thats the question)
public class Orchestrator {
@Inject
private DataGetter dataGetter;
public void doWork() {
FileWriter writer = new FileWriter("filename");
// Write the formatted data to the file
dataGetter.getData()
.forEach(data -> writer.writeToFile(data));
}
}
public class FileWriter {
public void writeToFile(List data) {
// Write to file
}
}
public class DataGetter {
@Inject
private ThingDao thingDao;
public Something getData() {
// Map data to the correct format and return that
return thingDao.getThings()
.map(partialResult -> /* map to object */);
}
}
public class ThingDao {
public Something getThings() {
Query q = ...;
// Dont know what to return
}
}
I tried to go from the base of an Iterator, because it's the only one that really fulfills my memory требования. Затем я добавил несколько методов для картирования и зацикливания по данным. It's not really a robust design though and it's going to be harder than I thought, so I wanted to know if there is anything out there already that does what I need.
Код: Выделить всё
public class QIterator implements Iterator {
public static String QUERY_OFFSET = "queryOffset";
public static String QUERY_LIMIT = "queryLimit";
private Query query;
private long lastResultIndex = 0;
private long batchSize;
private Function mapper;
public QIterator(Query query, long batchSize) {
this.query = query;
this.batchSize = batchSize;
}
public QIterator(Query query, long batchSize, Function mapper) {
this(query, batchSize);
this.mapper = mapper;
}
@Override
public boolean hasNext() {
return lastResultIndex % batchSize == 0;
}
@Override
public List next() {
query.setParameter(QueryIterator.QUERY_OFFSET, lastResultIndex);
query.setParameter(QueryIterator.QUERY_LIMIT, batchSize);
List result = (List) query.getResultList(); // unchecked
lastResultIndex += result.size();
List mappedResult;
if (mapper != null) {
mappedResult = mapper.apply(result);
} else {
mappedResult = (List) result; // unchecked
}
return mappedResult;
}
public QIterator map(Function appendingMapper) {
return new QIterator(query, batchSize, (data) -> {
if (this.mapper != null) {
return appendingMapper.apply(this.mapper.apply(data));
} else {
return appendingMapper.apply((List) data);
}
});
}
public void forEach(BiConsumer consumer) {
for (int i = 0; this.hasNext(); i++) {
consumer.accept(this.next(), i);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/635 ... ke-streams