Java Code Examples for java.util.List.subList()

The following are Jave code examples for showing how to use subList() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ijcnlp2017-cmaps   File: FeatureExtractor.java   View Source Code Vote up 6 votes
private Map<Integer, Map<String, Double>> loadGraphFeatures(int topic) {
	// concept -> feature_name -> value
	Map<Integer, Map<String, Double>> data = new HashMap<Integer, Map<String, Double>>();
	String fileName = this.baseFolder + "/" + topic + "/" + this.graphFile;
	try {
		List<String> lines = FileUtils.readLines(new File(fileName), Charsets.UTF_8);
		String[] header = lines.get(0).split("\t");
		for (String line : lines.subList(1, lines.size())) {
			String[] cols = line.split("\t");
			int id = Integer.parseInt(cols[0]);
			Map<String, Double> features = new HashMap<String, Double>();
			for (int i = 1; i < cols.length; i++)
				features.put(header[i], Double.parseDouble(cols[i]));
			data.put(id, features);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	return data;
}
 
Example 2
Project: OOP-ActParser   File: ElementParser.java   View Source Code Vote up 6 votes
/**
 * Identifies main parts of the parsed element and sets them in the
 * parser's fields.
 *
 * @param linesToParse
 */
protected void parseStructure(List<String> linesToParse) {
    Matcher startMatcher = getStartPattern().matcher(linesToParse.get(0));

    // locate capture groups
    startMatcher.find();

    idString = startMatcher.group(1);
    title = startMatcher.group(2);
    String bodyInFirstLine = startMatcher.group(3);

    if (bodyInFirstLine.trim().isEmpty()) {
        bodyLines = linesToParse.subList(1, linesToParse.size());
    } else {
        // pass leftover text to children parsers
        linesToParse.set(0, bodyInFirstLine);
        bodyLines = linesToParse;
    }
}
 
Example 3
Project: incubator-netbeans   File: SetUpRemotePlatform.java   View Source Code Vote up 6 votes
private static int jreCreate(@NonNull final List<String> cmdLine) {
    ExternalProcessBuilder pb = new ExternalProcessBuilder(cmdLine.get(0));
    pb = pb.addEnvironmentVariable(
        ENV_JAVA_HOME,
        FileUtil.toFile(JavaPlatform.getDefault().getInstallFolders().iterator().next()).getAbsolutePath());
    for (String arg : cmdLine.subList(1, cmdLine.size())) {
        pb = pb.addArgument(arg);
    }
    int res;
    try {
        final Process process = pb.call();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = in.readLine())!= null) {
                System.out.println(line);
            }
        }
        process.waitFor();
        res = process.exitValue();
    } catch (IOException | InterruptedException e) {
        res = -1;
    }
    return res;
}
 
Example 4
Project: openjdk-jdk10   File: SubList.java   View Source Code Vote up 6 votes
/**
 * Lists that don't allow resizing, but allow setting values
 */
@DataProvider
public static Object[][] unresizable() {
    final List<Integer> c1 = Arrays.asList(42);
    final List<Integer> c9 = Arrays.asList(40, 41, 42, 43, 44, 45, -1,
            Integer.MIN_VALUE, 1000500);

    Object[][] l1 = unsettable();
    Object[][] l2 = {
        {c1, 0, 1},
        {c1.subList(0, 1), 0, 1},
        {Collections.checkedList(c1, Integer.class), 0, 1},
        {Collections.synchronizedList(c1), 0, 1},
        {c9, 0, 4},
        {c9, 4, 6},
        {c9.subList(1, 8), 1, 4},
        {c9.subList(1, 8), 0, 7},
        {Collections.checkedList(c9, Integer.class), 3, 6},
        {Collections.synchronizedList(c9), 3, 5},
    };
    Object[][] res = Arrays.copyOf(l1, l1.length + l2.length);
    System.arraycopy(l2, 0, res, l1.length, l2.length);
    return res;
}
 
Example 5
Project: dockerized-microservices   File: PasswordsService.java   View Source Code Vote up 6 votes
/**
 * Find passwords end point
 * @param request Find password query
 * @param responseObserver Response observer
 */
@Override
public void findPasswords(FindPasswordsQuery request, StreamObserver<FindPasswordsResponse> responseObserver) {
    String prefix = request.getQuery();

    List<String> results = reader.getDict().findPrefixes(prefix);
    int totalMatches = results.size();

    if(totalMatches > maxResults) {
        results = results.subList(0, maxResults);
    }

    responseObserver.onNext(FindPasswordsResponse.newBuilder()
            .addAllMatches(results)
            .setNumOfMatches(totalMatches)
            .build());

    responseObserver.onCompleted();
}
 
Example 6
Project: cornerstone   File: IgniteStatus.java   View Source Code Vote up 6 votes
public static GetLastStatusResp getLastStatus(GetLastStatusReq req) throws Exception {
    IgniteStatus currentStatus = ComponentManager.getStatus(IgniteStatus.class);

    GetLastStatusResp resp = new GetLastStatusResp();
    List<String> msgs = currentStatus.getMessages();
    if(msgs.size()>=req.msgIndex) {
        currentStatus.refresh();
        resp.status = currentStatus.getStatus();
        resp.currentPluginIndex = currentStatus.getCurrentPluginIndex();
        if(req.msgIndex<msgs.size()-1) {
            resp.messages = msgs.subList(req.msgIndex, msgs.size() - 1);
        }
        resp.cost = currentStatus.getCost();
    }

    return resp;

}
 
Example 7
Project: ARCLib   File: IndexStore.java   View Source Code Vote up 5 votes
/**
 * Load configuration from a CSV file defining ARCLib XML.
 *
 * @return Set with config object for each index field.
 * @throws IOException
 */
default Set<IndexFieldConfig> getFieldsConfig() throws IOException {
    List<String> fieldsDefinitions = Files.readAllLines(Paths.get("src/main/resources/index/fieldDefinitions.csv"));
    Set<IndexFieldConfig> fieldConfigs = new HashSet<>();
    for (String line :
            fieldsDefinitions.subList(1, fieldsDefinitions.size())) {
        String arr[] = line.split(",");
        if (arr.length != 8)
            throw new IllegalArgumentException(String.format("fieldDefinitions.csv can't contain row with empty column: %s", line));
        if (!arr[5].equals("fulltext") && !arr[5].equals("atribut"))
            fieldConfigs.add(new IndexFieldConfig(arr[5], arr[6], arr[7], "N" .equals(arr[2])));
    }
    return fieldConfigs;
}
 
Example 8
Project: sstore-soft   File: Iterators.java   View Source Code Vote up 5 votes
private static <T> UnmodifiableIterator<List<T>> partitionImpl(
    final Iterator<T> iterator, final int size, final boolean pad) {
  checkNotNull(iterator);
  checkArgument(size > 0);
  return new UnmodifiableIterator<List<T>>() {
    @Override
    public boolean hasNext() {
      return iterator.hasNext();
    }
    @Override
    public List<T> next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      Object[] array = new Object[size];
      int count = 0;
      for (; count < size && iterator.hasNext(); count++) {
        array[count] = iterator.next();
      }
      for (int i = count; i < size; i++) {
        array[i] = null; // for GWT
      }

      @SuppressWarnings("unchecked") // we only put Ts in it
      List<T> list = Collections.unmodifiableList(
          (List<T>) Arrays.asList(array));
      return (pad || count == size) ? list : list.subList(0, count);
    }
  };
}
 
Example 9
Project: openjdk-jdk10   File: SubList.java   View Source Code Vote up 5 votes
@Test(dataProvider = "modifiable",
      expectedExceptions = ConcurrentModificationException.class)
public void testModListIteratorNext(List<Integer> list, int from, int to) {
    List<Integer> subList = list.subList(from, to);
    ListIterator<Integer> it = subList.listIterator();
    list.add(42);
    it.next();
}
 
Example 10
Project: hyperrail-for-android   File: PersistentQueryProvider.java   View Source Code Vote up 5 votes
/**
 * Get favorite and recent stations, and apply user preferences (order, count)
 *
 * @return Sorted array with favorite and recent station names
 */
public List<Suggestion<StationSuggestion>> getAllStations() {
    int recentLimit = Integer.valueOf(sharedPreferences.getString("stations_history_count", "3"));
    int order = Integer.valueOf(sharedPreferences.getString("stations_order", "0"));
    // 0 || 2: recents before favorites
    // 1 || 3: favorites before recents

    List<Suggestion<StationSuggestion>> favorites = getStations(FAVORITE);

    if (recentLimit == 0) {
        return favorites;
    }

    // Keep some margin to ensure that we will always show the number of recents set by the user
    List<Suggestion<StationSuggestion>> recents = getStations(HISTORY, recentLimit + favorites.size());

    recents = (List<Suggestion<StationSuggestion>>) removeFromCollection(recents, favorites);

    if (recents.size() > recentLimit) {
        recents = recents.subList(0, recentLimit);
    }

    if (order == 0 || order == 2) {
        recents.addAll(favorites);
        return recents;
    } else {
        favorites.addAll(recents);
        return favorites;
    }
}
 
Example 11
Project: autopivot   File: CSVDiscovery.java   View Source Code Vote up 5 votes
/**
 * 
 * Discover the CSV format of a CSV file.
 * 
 * @param fileName
 * @param charset
 * @return CSV Format
 * @throws IOException
 */
public CSVFormat discoverFile(String fileName, Charset charset) throws IOException {
	
	LOG.info("Detecting CSV parser configuration for file " + fileName);
	
	InputStream is = openFile(fileName);
	try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
		List<String> lines = reader.lines().limit(1000L).collect(Collectors.toList());
		if(lines.size() <= 0) {
			throw new QuartetRuntimeException("Cannot process empty file: " + fileName);
		}
		
		String separator = detectSeparator(lines);

		LOG.info("Detected separator: " + separator);
		
		// Extract column names from header
		List<String> headers = Arrays.asList(CSVSplitter.split(lines.get(0), separator));
		
		LOG.info("Column names: " + headers);
		
		// Remove header and detect column types
		List<String> content = lines.subList(1, lines.size());
		List<List<String>> columns = toColumns(content, separator);
		List<String> types = new ArrayList<>(columns.size());
		for(List<String> column : columns) {
			String type = detectType(column);
			types.add(type);
		}

		LOG.info("Detected types: " + types);
		
		return new CSVFormat(separator, headers, types);
	}
}
 
Example 12
Project: tumbviewer   File: DashboardPresenter.java   View Source Code Vote up 5 votes
private List<PostsItem> removeDuplicate(List<PostsItem> postsItems) {
        int i = 0;
        for (; i < postsItems.size(); i++) {
            if (lastTimestamp > postsItems.get(i).getTimestamp()) {
                break;
            }
        }
        if (i > 0 && i < postsItems.size()) {
            postsItems = postsItems.subList(i, postsItems.size());
//        } else if (i >= postsItems.size()) {
//            postsItems.clear();
            //this case is complicated, don't clear, just show them.
        }
        return postsItems;
    }
 
Example 13
Project: spring-data-ebean   File: AbstractEbeanQueryExecution.java   View Source Code Vote up 5 votes
@Override
@SuppressWarnings("unchecked")
protected Object doExecute(AbstractEbeanQuery query, Object[] values) {

  ParametersParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
  Pageable pageable = accessor.getPageable();

  Object createQuery = query.createQuery(values);
  List<Object> resultList = null;
  int pageSize = pageable.getPageSize();
  if (createQuery instanceof Query) {
    Query ormQuery = (Query) createQuery;
    ormQuery.setMaxRows(pageSize + 1);

    ormQuery.findList();
  } else if (createQuery instanceof SqlQuery) {
    SqlQuery sqlQuery = (SqlQuery) createQuery;

    sqlQuery.setMaxRows(pageSize + 1);

    sqlQuery.findList();
  } else {
    throw new InvalidEbeanQueryMethodException("query must be Query or SqlQuery");
  }

  boolean hasNext = resultList != null && resultList.size() > pageSize;

  return new SliceImpl<Object>(hasNext ? resultList.subList(0, pageSize) : resultList, pageable, hasNext);
}
 
Example 14
Project: smaph   File: SmaphBuilder.java   View Source Code Vote up 4 votes
public static SmaphAnnotator getSmaph(SmaphVersion v, WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb,
        WAT2Annotator auxAnnotator, EntityToAnchors e2a, boolean includeS2, Websearch ws, SmaphConfig c, int greedyStepLimit)
        throws FileNotFoundException, ClassNotFoundException, IOException {
	URL model = getDefaultModel(v, ws, true, includeS2, true, -1);
	URL zscore = getDefaultZscoreNormalizer(v, ws, true, includeS2, true, -1);

	SmaphAnnotator a = null;
	switch (v) {
	case ANNOTATION_REGRESSOR: {
		AnnotationRegressor ar = getCachedAnnotationRegressor(model);
		FeatureNormalizer fn = getCachedFeatureNormalizer(zscore, new GreedyFeaturePack());
		a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null,
		        new IndividualLinkback(ar, fn, wikiApi, wikiToFreeb, e2a, DEFAULT_ANCHOR_MENTION_ED), true, includeS2,
		        true, ws, c);
	}
		break;
	case ENTITY_FILTER: {
		EntityFilter ef = getCachedSvmEntityFilter(model);
		FeatureNormalizer norm = getCachedFeatureNormalizer(zscore, new EntityFeaturePack());
		a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, ef, norm, new DummyLinkBack(), true, includeS2,
		        true, ws, c);
	}
		break;
	case COLLECTIVE: {
		BindingRegressor bindingRegressor = getCachedBindingRegressor(model);
		CollectiveLinkBack lb = new CollectiveLinkBack(wikiApi, wikiToFreeb, e2a, new DefaultBindingGenerator(),
		        bindingRegressor, new NoFeatureNormalizer());
		a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null, lb, true, includeS2,
		        true, ws, c);
	}
		break;
	case GREEDY: {
		Pair<List<AnnotationRegressor>,List<FeatureNormalizer> > regressorsAndNormalizers = getGreedyRegressors(ws, true, includeS2, true);
		List<AnnotationRegressor> regressors = regressorsAndNormalizers.getFirst();
		List<FeatureNormalizer> normalizers = regressorsAndNormalizers.getSecond();
		if (regressors.isEmpty())
			throw new IllegalArgumentException("Could not find models.");

		if (greedyStepLimit >= 0){
			regressors = regressors.subList(0, greedyStepLimit);
			normalizers = normalizers.subList(0, greedyStepLimit);
		}
		
		GreedyLinkback lbGreedy = new GreedyLinkback(regressors, normalizers, wikiApi, wikiToFreeb, e2a, DEFAULT_ANCHOR_MENTION_ED);
		a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null, lbGreedy, true,
		        includeS2, true, ws, c);
	}
		break;

	default:
		throw new NotImplementedException();
	}
	a.appendName(String.format(" - %s, %s%s", v, ws, includeS2 ? "" : ", excl. S2"));

	return a;
}
 
Example 15
Project: openjdk-jdk10   File: RemoveMicroBenchmark.java   View Source Code Vote up 4 votes
private static <T> List<T> asSubList(List<T> list) {
    return list.subList(0, list.size());
}
 
Example 16
Project: algo-kit   File: MergeSort.java   View Source Code Vote up 4 votes
private List<K> partition(final List<K> input, final int start, final int end) {
    return input.subList(start, end+1);
}
 
Example 17
Project: ShowScraper   File: GetSongList.java   View Source Code Vote up 4 votes
public static List<Song> getShortSongList(int numItems) {
	List<Song> songList = getSongList(false);
	
	return songList.subList(0, numItems);
}
 
Example 18
Project: jdk8u-jdk   File: MethodHandles.java   View Source Code Vote up 4 votes
/**
 * Makes a method handle which adapts a target method handle,
 * by running it inside an exception handler.
 * If the target returns normally, the adapter returns that value.
 * If an exception matching the specified type is thrown, the fallback
 * handle is called instead on the exception, plus the original arguments.
 * <p>
 * The target and handler must have the same corresponding
 * argument and return types, except that handler may omit trailing arguments
 * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
 * <p> Here is pseudocode for the resulting adapter:
 * <blockquote><pre>{@code
 * T target(A..., B...);
 * T handler(ExType, A...);
 * T adapter(A... a, B... b) {
 *   try {
 *     return target(a..., b...);
 *   } catch (ExType ex) {
 *     return handler(ex, a...);
 *   }
 * }
 * }</pre></blockquote>
 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
 * be modified by execution of the target, and so are passed unchanged
 * from the caller to the handler, if the handler is invoked.
 * <p>
 * The target and handler must return the same type, even if the handler
 * always throws.  (This might happen, for instance, because the handler
 * is simulating a {@code finally} clause).
 * To create such a throwing handler, compose the handler creation logic
 * with {@link #throwException throwException},
 * in order to create a method handle of the correct return type.
 * @param target method handle to call
 * @param exType the type of exception which the handler will catch
 * @param handler method handle to call if a matching exception is thrown
 * @return method handle which incorporates the specified try/catch logic
 * @throws NullPointerException if any argument is null
 * @throws IllegalArgumentException if {@code handler} does not accept
 *          the given exception type, or if the method handle types do
 *          not match in their return types and their
 *          corresponding parameters
 */
public static
MethodHandle catchException(MethodHandle target,
                            Class<? extends Throwable> exType,
                            MethodHandle handler) {
    MethodType ttype = target.type();
    MethodType htype = handler.type();
    if (htype.parameterCount() < 1 ||
        !htype.parameterType(0).isAssignableFrom(exType))
        throw newIllegalArgumentException("handler does not accept exception type "+exType);
    if (htype.returnType() != ttype.returnType())
        throw misMatchedTypes("target and handler return types", ttype, htype);
    List<Class<?>> targs = ttype.parameterList();
    List<Class<?>> hargs = htype.parameterList();
    hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
    if (!targs.equals(hargs)) {
        int hpc = hargs.size(), tpc = targs.size();
        if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
            throw misMatchedTypes("target and handler types", ttype, htype);
        handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
        htype = handler.type();
    }
    return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
}
 
Example 19
Project: jijimaku   File: AnnotationService.java   View Source Code Vote up 4 votes
/**
 * Return all the dictionary matches for one caption.
 * For example the parsed sentence => I|think|he|made|it|up should likely return four
 * DictionaryMatches => I|to think|he|to make it up
 */
private List<DictionaryMatch> getDictionaryMatches(String caption) {
  // A syntaxic parse of the caption returns a list of tokens.
  List<TextToken> captionTokens = langParser.syntaxicParse(caption);

  // Next we must group tokens together if they is a corresponding definition in the dictionary.
  List<DictionaryMatch> matches = new ArrayList<>();
  while (!captionTokens.isEmpty()) {

    // Skip token that are not words or should be ignored
    if (POS_TAGS_NOT_WORD.contains(captionTokens.get(0).getPartOfSpeech())
        || POS_TAGS_IGNORE_WORD.contains(captionTokens.get(0).getPartOfSpeech())) {
      captionTokens = captionTokens.subList(1, captionTokens.size());
      continue;
    }

    // Find the next DictionaryMatch
    // Start with all tokens and remove one by one until we have a match
    List<TextToken> maximumTokens = new ArrayList<>(captionTokens);
    DictionaryMatch match = dictionaryMatch(maximumTokens);
    while (match == null && maximumTokens.size() > 0) {
      maximumTokens = maximumTokens.subList(0, maximumTokens.size() - 1);
      match = dictionaryMatch(maximumTokens);
    }

    if (match == null) {
      // We could not find a match for current token, just remove it
      captionTokens = captionTokens.subList(1, captionTokens.size());
      continue;
    }

    // Do not accept the match if it is a short sequence of hiragana
    // because it is most likely a wrong grouping of independent grammar conjunctions
    // and unlikely to be an unusual word that needs to be defined
    // (but make an exception for verbs)
    if (match.getTextForm().length() <= 3 && IS_HIRAGANA_RE.matcher(match.getTextForm()).matches() && !match.hasVerb()) {
      captionTokens = captionTokens.subList(1, captionTokens.size());
      continue;
    }

    matches.add(match);
    captionTokens = captionTokens.subList(match.getTokens().size(), captionTokens.size());

  }
  return matches;
}
 
Example 20
Project: cloudcard-csv-importer   File: Main.java   View Source Code Vote up 2 votes
private static List<String> dropHeaderFromList(List<String> lines) {

        return lines.subList(1, lines.size());
    }