Java tutorial
/* * Copyright Paolo Dragone 2014 * * This file is part of WiktionarySemanticNetwork. * * WiktionarySemanticNetwork is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WiktionarySemanticNetwork is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with WiktionarySemanticNetwork. If not, see <http://www.gnu.org/licenses/>. */ package com.paolodragone.util.io.datasets.tsv; import com.google.common.collect.ImmutableList; import com.paolodragone.util.io.datasets.DataColumn; import com.paolodragone.util.io.datasets.DataRecord; import gnu.trove.map.TObjectShortMap; import gnu.trove.map.hash.TObjectShortHashMap; import org.apache.commons.csv.CSVRecord; import java.util.Collection; import java.util.Iterator; /** * Wrapper for {@link org.apache.commons.csv.CSVRecord} to use it with {@link TsvDataSet}. * * @author Paolo Dragone */ public final class TsvDataRecord implements DataRecord { private final TObjectShortMap<String> mapping = new TObjectShortHashMap<>(); private final ImmutableList<String> values; TsvDataRecord(CSVRecord record, DataColumn[] header) { if (header.length > Short.MAX_VALUE) { throw new IllegalStateException("Current header has too many columns."); } ImmutableList.Builder<String> builder = ImmutableList.builder(); for (short i = 0; i < header.length; i++) { DataColumn key = header[i]; mapping.put(key.getColumnName(), i); builder.add(record.get(key.getColumnName())); } values = builder.build(); } @Override public String get(DataColumn column) { if (!mapping.containsKey(column.getColumnName())) { throw new IllegalArgumentException( String.format("No mapping for column '%s'.", column.getColumnName())); } return values.get(mapping.get(column.getColumnName())); } @Override public Collection<String> values() { return values; } @Override public Iterator<String> iterator() { return values.iterator(); } }