All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.daredayo.util.collection.ContinuousLongPeriod Maven / Gradle / Ivy

package com.daredayo.util.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;


public class ContinuousLongPeriod implements Supplier>{
	
	final List periods;
	final Supplier supplier;
	
	int index;
	int last;
	
	Long lastValue;
	public ContinuousLongPeriod(long... periods){
		
		supplier = null;
		this.periods = new ArrayList();
		for (long period : periods) {
			this.periods.add(period);
		}
		index = 0;
		last = periods.length-1;
	}
	
	public ContinuousLongPeriod(Supplier supplier){
		periods = null;
		this.supplier = supplier;
	}
	
	public ContinuousLongPeriod(){
		periods = new ArrayList();
		this.supplier = null;
		last=-1;
	}
	
	public void add(Long period){
		periods.add(period);
		last++;
	}

	
	@Override
	public Optional get() {
		
		if(supplier != null){
			if(lastValue == null){
				lastValue = supplier.get();
			}
			long current = supplier.get();
			LongPeriod longPeriod = new LongPeriod(lastValue , current);
			lastValue = current;
			return Optional.of(longPeriod);
		}
		if(index == last ){
			return Optional.empty();
		}
		return Optional.of(new LongPeriod(periods.get(index), periods.get(++index)));
	}
	
	protected List getList(){
		
		index=0;
		List results = new ArrayList();
		
		while(true){
			
			Optional current = get();
			if(false == current.isPresent()){
				break;
			}
			current.ifPresent(results::add);
		}
		return results;
	}
	
	public Stream stream(){
		
		return getList().stream();
	}
	
	public Optional getOverall(){
		
		if(supplier != null){
			throw new IllegalStateException("this method not support with constructed as Supplier instance");
		}
		if(periods.isEmpty()){
			return Optional.empty();
		}
		return Optional.of(new LongPeriod(periods.get(0), periods.get(periods.size()-1)));
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy