001/*
002 * Copyright (c) 2015-2020, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.datasource;
018
019import org.tribuo.DataSource;
020import org.tribuo.Example;
021import org.tribuo.Output;
022import org.tribuo.OutputFactory;
023import org.tribuo.provenance.DataSourceProvenance;
024
025import java.util.ArrayList;
026import java.util.Collections;
027import java.util.Iterator;
028import java.util.List;
029
030/**
031 * A data source which wraps up a list of {@link Example}s
032 * along with their {@link DataSourceProvenance} and an {@link OutputFactory}.
033 * <p>
034 * Used for machine generated data, or some other place where it's difficult to
035 * write a specific data source.
036 */
037public class ListDataSource<T extends Output<T>> implements DataSource<T> {
038
039    private final List<Example<T>> data;
040
041    private final OutputFactory<T> factory;
042
043    private final DataSourceProvenance provenance;
044
045    public ListDataSource(List<Example<T>> list, OutputFactory<T> factory, DataSourceProvenance provenance) {
046        this.data = Collections.unmodifiableList(new ArrayList<>(list));
047        this.factory = factory;
048        this.provenance = provenance;
049    }
050
051    /**
052     * Number of examples.
053     * @return The number of examples.
054     */
055    public int size() {
056        return data.size();
057    }
058
059    @Override
060    public OutputFactory<T> getOutputFactory() {
061        return factory;
062    }
063
064    @Override
065    public DataSourceProvenance getProvenance() {
066        return provenance;
067    }
068
069    @Override
070    public Iterator<Example<T>> iterator() {
071        return data.iterator();
072    }
073
074    @Override
075    public String toString() {
076        return provenance.toString();
077    }
078}