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

The following are Jave code examples for showing how to use subList() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Algorithms-4-everyone   File: MergeSort.java   Source Code and License Vote up 6 votes
private void merge(ArrayList<T> listToSort, int start, int middle, int end) {
    ArrayList<T> A = new ArrayList<T>(listToSort.subList(start, middle + 1));
    ArrayList<T> B = new ArrayList<T>(listToSort.subList(middle + 1, end + 1));
    A.add(A.get(0).getMaxObject());
    B.add(B.get(0).getMaxObject());

    int i = 0;
    int j = 0;

    for (int k = start; k <= end; k++) {
        if (A.get(i).compareTo(B.get(j)) <= 0) {
            listToSort.set(k, A.get(i));
            i++;
        } else {
            listToSort.set(k, B.get(j));
            j++;
        }
    }
}
 
Example 2
Project: Musicoco   File: RecentMostPlayActivity.java   Source Code and License Vote up 6 votes
private void LoadData() {
    MainSheetHelper helper = new MainSheetHelper(this, dbController);
    List<DBSongInfo> info = helper.getMainSheetSongInfo(MainSheetHelper.SHEET_ALL);
    ArrayList<DBSongInfo> result = DBSongInfo.descSortByPlayTimes(info);

    int count = getResources().getInteger(R.integer.rmp_count);
    count = count > result.size() ? result.size() : count;
    // 左闭右开
    for (DBSongInfo in : result.subList(0, count)) {
        RMPAdapter.DataHolder da = new RMPAdapter.DataHolder();
        da.times = in.playTimes;

        SongInfo songInfo = mediaManager.getSongInfo(this, in.path);
        String title = songInfo.getTitle();
        String arts = songInfo.getArtist();
        String albumP = songInfo.getAlbum_path();

        da.album = albumP;
        da.title = title;
        da.arts = arts;
        da.path = in.path;

        data.add(da);
    }

}
 
Example 3
Project: EsperantoRadio   File: BasisAfprøvning.java   Source Code and License Vote up 6 votes
public void tjek_hent_a_til_å() throws Exception {
  System.out.println("tjek_hent_a_til_å");
  backend.hentAlleProgramserierAtilÅ(NetsvarBehander.TOM);
  ArrayList<Programserie> liste = App.data.programserierAtilÅ.getListe();
  System.out.println("tjek_hent_a_til_å liste="+liste.size());
  assertTrue(liste.size()>0);

  int samletAntalUdsendelser = 0;

  // Tjek kun nummer 50 til nummer 100
  for (Programserie ps : liste.subList(50, 65)) {
    backend.hentProgramserie(ps, ps.slug, null, 0, NetsvarBehander.TOM);
    ArrayList<Udsendelse> udsendelser = ps.getUdsendelser();

    System.out.println(ps.slug + " " + ps.antalUdsendelser + " " + udsendelser.size());
    assertTrue(ps.slug + " har færre udsendelser end påstået:\n"+ps.titel, ps.antalUdsendelser>= udsendelser.size());
    samletAntalUdsendelser += udsendelser.size();
  }
  assertTrue("Kun "+samletAntalUdsendelser+" udsendelser!", samletAntalUdsendelser>10);
}
 
Example 4
Project: medialibrary   File: ClusterAlbum.java   Source Code and License Vote up 6 votes
public static ArrayList<MediaItem> getMediaItemFromPath(
        ArrayList<Path> paths, int start, int count,
        DataManager dataManager) {
    if (start >= paths.size()) {
        return new ArrayList<MediaItem>();
    }
    int end = Math.min(start + count, paths.size());
    ArrayList<Path> subset = new ArrayList<Path>(paths.subList(start, end));
    final MediaItem[] buf = new MediaItem[end - start];
    ItemConsumer consumer = new ItemConsumer() {
        @Override
        public void consume(int index, MediaItem item) {
            buf[index] = item;
        }
    };
    dataManager.mapMediaItems(subset, consumer, 0);
    ArrayList<MediaItem> result = new ArrayList<>();
    for (int i = 0; i < buf.length; i++) {
        if(buf[i]!=null) {
            result.add(buf[i]);
        }
    }
    return result;
}
 
Example 5
Project: cyp2sql   File: WithSQL.java   Source Code and License Vote up 6 votes
private static StringBuilder getOrderByForWith(StringBuilder sWith, ArrayList<String> tokens) {
    int posOfOrder = tokens.indexOf("order");
    sWith.append(" ORDER BY ");

    tokens = new ArrayList<>(tokens.subList(posOfOrder, tokens.size()));

    // deals with clauses such as ORDER BY <alias> ASC/DESC
    if (tokens.size() == 3 || tokens.size() == 4) {
        sWith.append(tokens.get(2)).append(" ").append((tokens.size() == 4) ? tokens.get(3) : "ASC");
        return sWith;
    }

    while (true) {
        String field = tokens.get(4);
        String dir = (tokens.get(5).equals("asc") || tokens.get(5).equals("desc")) ? tokens.get(5) : null;
        sWith.append(field).append(" ").append((dir == null) ? "" : dir);

        int posOfComma = tokens.indexOf(",");
        if (posOfComma == -1) break;
        else tokens = new ArrayList<>(tokens.subList(posOfComma + 1, tokens.size()));
    }
    return sWith;
}
 
Example 6
Project: loom   File: TimingBag.java   Source Code and License Vote up 6 votes
/**
 * Record the time for given lid, this is then stored to produce min/max/avg from.
 *
 * @param value timing to store
 */
public void recordTime(final long value) {
    runIdx++;
    latestTime = value;
    if (value < minTime) {
        minTime = value;
    }
    if (value > maxTime) {
        maxTime = value;
    }
    avgTime += value;
    // is it in topList?
    if (value > topList.get(topNbr - 1)) {
        ArrayList<Long> newTopList = new ArrayList<>(topList);
        newTopList.add(value);
        Collections.sort(newTopList, Collections.reverseOrder());
        topList = new ArrayList<>(newTopList.subList(0, topNbr));
    }
}
 
Example 7
Project: x7   File: AsyncDaoImpl.java   Source Code and License Vote up 5 votes
/**
 * 批处理的执行<br>
 * 在内部线程里调用
 */
@SuppressWarnings({ "rawtypes" })
private void executeCreate(final Map<Class, ArrayList<Object>> tempMap)
		throws Exception {
	for (Class clz : tempMap.keySet()) {

		ArrayList<Object> objList = tempMap.get(clz);
		
		String sql = MapperFactory.getSql(clz, Mapper.CREATE);
		
		List<BeanElement> eles = MapperFactory.getElementList(clz);
		
		/*
		 * 分段批处理,每段不超过MAX_BATCH
		 */
		int size = objList.size();
		int times = size / MAX_BATCH + 1;

		for (int i = 0; i < times; i++) {

			int segment = 0;
			if (i + 1 == times) {
				segment = size % MAX_BATCH;
				if (segment == 0){
					break;
				}
			}else{
				segment = MAX_BATCH;
			}
			
			int fromIndex = i * MAX_BATCH;
			List<Object> subList = objList.subList(fromIndex, fromIndex + segment);
			batchCreate(subList, sql, eles);
			
		}

	}
}
 
Example 8
Project: xsharing-services-router   File: RasterManagerImpl.java   Source Code and License Vote up 5 votes
/**
 * Obtain partial set of the raster
 * @param from lower index
 * @param to upper index
 * @return list of the contained raster points at the provided indices, or null if invalid
 */
@Override
public List<RasterPoint> getSubList(int from, int to) {
    ArrayList<RasterPoint> values = new ArrayList<>(points.values());
    try {
        int size = values.size();
        if (to >= size && from < size) {
            return values.subList(from, size - 1);
        }
        return values.subList(from, to);
    } catch (IndexOutOfBoundsException ie) {
        log.error("The provided indices were invalid! from={}, to={}", from, to);
        return null;
    }
}
 
Example 9
Project: InfixToObject   File: BinaryOperatorRepresentation.java   Source Code and License Vote up 5 votes
@Override
public IEquation<T> convert(ArrayList<IElementRepresentation<T>> equation) throws ConvertionException {
	if(equation == null || equation.size() < 2) {
		throw new ConvertBinaryOperatorException();
	}
	
	int rightOperandStartIndex = getRightOperandStartIndex(equation);
	ArrayList<IElementRepresentation<T>> leftEquationRepresentation = new ArrayList<>(equation.subList(0, rightOperandStartIndex));
	ArrayList<IElementRepresentation<T>> rightEquationRepresentation = new ArrayList<>(equation.subList(rightOperandStartIndex, equation.size()));
	
	IEquation<T> leftEquation = leftEquationRepresentation.get(0).convert(new ArrayList<>(leftEquationRepresentation.subList(1, leftEquationRepresentation.size())));
	IEquation<T> rightEquation = rightEquationRepresentation.get(0).convert(new ArrayList<>(rightEquationRepresentation.subList(1, rightEquationRepresentation.size())));
	
	return build(leftEquation, rightEquation);
}
 
Example 10
Project: knime-activelearning   File: ValueIndexPairTest.java   Source Code and License Vote up 5 votes
@Test
public void testGetKRandomMaxima() {
    final double[] array = new double[100];
    for (int i = 0; i < array.length; i++) {
        array[i] = Math.random();
    }
    final ValueIndexPair[] valIndexArray =
            ValueIndexPair.transformArray2ValueIndexPairArray(array);
    final ArrayList<ValueIndexPair> expectedFullList =
            new ArrayList<ValueIndexPair>(Arrays.asList(valIndexArray));

    final Comparator<ValueIndexPair> comparator =
            new Comparator<ValueIndexPair>() {
                @Override
                public int compare(final ValueIndexPair o1,
                        final ValueIndexPair o2) {
                    if (o1.getValue() < o2.getValue()) {
                        return 1;
                    } else if (o1.getValue() > o2.getValue()) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            };

    expectedFullList.sort(comparator);
    final List<ValueIndexPair> expected = expectedFullList.subList(0, 19);

    final ArrayList<ValueIndexPair> result =
            new ArrayList<ValueIndexPair>(Arrays.asList(
                    ValueIndexPair.getK(valIndexArray, 20, comparator)));

    for (final ValueIndexPair pair : expected) {
        assertTrue(result.contains(pair));
    }
}
 
Example 11
Project: AOSP-Kayboard-7.1.2   File: AndroidWordLevelSpellCheckerSession.java   Source Code and License Vote up 5 votes
private static Result getResult(final int capitalizeType, final Locale locale,
        final int suggestionsLimit, final float recommendedThreshold, final String originalText,
        final SuggestionResults suggestionResults) {
    if (suggestionResults.isEmpty() || suggestionsLimit <= 0) {
        return new Result(null /* gatheredSuggestions */,
                false /* hasRecommendedSuggestions */);
    }
    final ArrayList<String> suggestions = new ArrayList<>();
    for (final SuggestedWordInfo suggestedWordInfo : suggestionResults) {
        final String suggestion;
        if (StringUtils.CAPITALIZE_ALL == capitalizeType) {
            suggestion = suggestedWordInfo.mWord.toUpperCase(locale);
        } else if (StringUtils.CAPITALIZE_FIRST == capitalizeType) {
            suggestion = StringUtils.capitalizeFirstCodePoint(
                    suggestedWordInfo.mWord, locale);
        } else {
            suggestion = suggestedWordInfo.mWord;
        }
        suggestions.add(suggestion);
    }
    StringUtils.removeDupes(suggestions);
    // This returns a String[], while toArray() returns an Object[] which cannot be cast
    // into a String[].
    final List<String> gatheredSuggestionsList =
            suggestions.subList(0, Math.min(suggestions.size(), suggestionsLimit));
    final String[] gatheredSuggestions =
            gatheredSuggestionsList.toArray(new String[gatheredSuggestionsList.size()]);

    final int bestScore = suggestionResults.first().mScore;
    final String bestSuggestion = suggestions.get(0);
    final float normalizedScore = BinaryDictionaryUtils.calcNormalizedScore(
            originalText, bestSuggestion, bestScore);
    final boolean hasRecommendedSuggestions = (normalizedScore > recommendedThreshold);
    return new Result(gatheredSuggestions, hasRecommendedSuggestions);
}
 
Example 12
Project: javaide   File: JavaClassReader.java   Source Code and License Vote up 5 votes
/**
 * search class with binary search
 *
 * @param simpleName - simple class name
 */
@Nullable
private List<Pair<String, Class>> binarySearch(ArrayList<Pair<String, Class>> classes, String simpleName) {
    //find left index
    int start = -1, end = -1;
    int left = 0;
    int right = classes.size() - 1;
    //search left most
    while (left <= right) {
        int mid = (left + right) / 2;
        String midValue = classes.get(mid).first.substring(0, Math.min(classes.get(mid).first.length(),
                simpleName.length()));
        if (midValue.compareTo(simpleName) < 0) { //mid < key
            left = mid + 1;
        } else if (midValue.compareTo(simpleName) > 0) {
            right = mid - 1;
        } else {
            start = mid;
            end = mid;
            //exit here
            while (start >= 0 && classes.get(start).first.substring(0, Math.min(classes.get(start).first.length(),
                    simpleName.length())).equals(simpleName)) {
                start--;
            }
            //exit here
            while (end < classes.size() && classes.get(end).first.substring(0, Math.min(classes.get(end).first.length(),
                    simpleName.length())).equals(simpleName)) {
                end++;
            }
            start++;
            end--;
            break;
        }
    }
    if (end >= 0 && start >= 0 && end - start + 1 >= 1) {
        return classes.subList(start, end + 1);
    }
    return null;
}
 
Example 13
Project: javaide   File: AutoCompleteProvider.java   Source Code and License Vote up 5 votes
private String join(ArrayList<String> items, int start, int end, String s) {
    List<String> strings = items.subList(start, end + 1);
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < strings.size(); i++) {
        result.append(strings.get(i)).append(i == strings.size() - 1 ? "" : s);
    }
    return result.toString();
}
 
Example 14
Project: javaide   File: GetSubListOfJavaArrayListExample.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {

    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    /*
       To get a sub list of Java ArrayList use
       List subList(int startIndex, int endIndex) method.
       This method returns an object of type List containing elements from
       startIndex to endIndex - 1.
    */

    List lst = arrayList.subList(1, 3);

    //display elements of sub list.
    System.out.println("Sub list contains : ");
    for (int i = 0; i < lst.size(); i++) System.out.println(lst.get(i));

    /*
      Sub List returned by subList method is backed by original Arraylist. So any
      changes made to sub list will also be REFLECTED in the original Arraylist.
    */
    //remove one element from sub list
    Object obj = lst.remove(0);
    System.out.println(obj + " is removed from sub list");

    //print original ArrayList
    System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
    for (int i = 0; i < arrayList.size(); i++) System.out.println(arrayList.get(i));
  }
 
Example 15
Project: music_player   File: Data.java   Source Code and License Vote up 4 votes
public  static void initialMusicDate(Context context){
    int number = 18;
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    String suggestion = sharedPref.getString("suggestion", "");
    switch (suggestion) {
        case "three":
            number = 3;
            break;
        case "six":
            number = 6;
            break;
        case "twelve":
            number =12;
            break;
        case "eighteen":
            number =18;
            break;
        default:
    }
    ArrayList<music_date> music_dates = new ArrayList<music_date>();
    _date = new Date[musicInfoArrayList.size()];

    for (int i = 0; i < musicInfoArrayList.size(); i++) {
        File music = new File(musicInfoArrayList.get(i).getMusicData());
        Date date = new Date(music.lastModified());
        _date[i] = date;
        music_dates.add(new music_date(i,_date[i]));
    }

    //从最近到之前排列
    Comparator<music_date> Datecomparator = new Comparator<music_date>() {
        @Override
        public int compare(music_date t1, music_date t2) {
            if (t1.getDate().before(t2.getDate())) {
                return 1;
            } else if (t1.getDate().after(t2.getDate())){
                return  -1;
            }else {
                return 0;
            }
        }

    };
    Collections.sort(music_dates,Datecomparator);
    //获取最近歌曲
    if (number >music_dates.size()){number = music_dates.size();}
    Datesublist = music_dates.subList(0,number);
}
 
Example 16
Project: java-chess   File: Board.java   Source Code and License Vote up 4 votes
public ArrayList<Move> getMoves(boolean color, boolean checkCheck) {
	ArrayList<Move> moves = new ArrayList<>();
	
	for(int i = 0; i < 8; i++)
		for(int j = 0; j < 8; j++) {
			if(tiles[i][j].isOccupied() && 
					tiles[i][j].getPiece().getColor() == color) {
				moves.addAll(tiles[i][j].getPiece().getMoves(this, i, j));
			}
		}
	
	// check if move is valid (must not be check after move) and throw away erroneous moves
	if(checkCheck) {
		// find king (of correct color)
		int x = -1, y = -1;
		for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++) {
				if(tiles[i][j].isOccupied() && 
						tiles[i][j].getPiece().getColor() == color &&
						tiles[i][j].getPiece().toString().equalsIgnoreCase("K")) {
					x = i; y = j;
				}
			}
		
		ArrayList<Move> removeThese = new ArrayList<Move>();
		for(int i = 0; i < moves.size(); i++) {
			// check a move if after making this move the king can be killed (moving into check)
			ArrayList<Move> checkThis = new ArrayList<Move>(moves.subList(i, i+1));
			ArrayList<Move> opponentMoves = getMovesAfter(!color, checkThis, false);
			
			int xUpdated = x, yUpdated = y;
			if(checkThis.get(0).getX1() == x && checkThis.get(0).getY1() == y) { // get updated king position
				xUpdated = checkThis.get(0).getX2();
				yUpdated = checkThis.get(0).getY2();
			}
			
			// check all opponent moves if they kill king (opponent moves in next round)
			for(int j = 0; j < opponentMoves.size(); j++) {
				if(opponentMoves.get(j).getX2() == xUpdated && opponentMoves.get(j).getY2() == yUpdated)
					removeThese.add(checkThis.get(0));
			}
		}
		
		moves.removeAll(removeThese); // remove invalid moves
	}
	
	return moves;
}
 
Example 17
Project: BrainControl   File: CooperationNegotiator.java   Source Code and License Vote up 4 votes
/**
 * the speaking agent verbalizes the goallist.
 * @param speakingAgent
 */
private void verbalizeGoalPlan(CAEAgent speakingAgent,ArrayList<GoalDistanceWrapper> goalPlan, boolean counterProposal){
	if(goalPlan != null && goalPlan.size() > 0) {
		
		Goal start = goalPlan.get(0).getPreviousInteraction();
		Goal end = null;
		List<GoalDistanceWrapper> body = null;
		if(goalPlan.size() > 1){
			end = goalPlan.get(goalPlan.size()-1).getPreviousInteraction();
		}
		
		if(goalPlan.size() > 2){
			body = goalPlan.subList(1, goalPlan.size()-1);
		}
		
		
		
		boolean cooperativeGoal = false;
		
		//checks if our goallist contains an interaction
		for(GoalDistanceWrapper goal :  goalPlan){
			if(!goal.getPreviousInteraction().getActor().equals(speakingAgent.getPlayer().getType())){
				cooperativeGoal = true;
			}
		}
		
		if(cooperativeGoal || counterProposal) {
			if(start != null) {
				verbalizeStart(start,speakingAgent);
			}
			if(body != null){
				verbalizeBody(body,speakingAgent);
			}
			if(end != null){
				verbalizeEnd(end,speakingAgent);
			}
		}
		if(counterProposal){
			
		}
	}
}
 
Example 18
Project: DeskChan   File: Words.java   Source Code and License Vote up 4 votes
public Words(ArrayList<String> words, int start, int end){
    this.words = new ArrayList<>(words.subList(start, end));
    this.used = new boolean[end - start];
    for(int i=0;i<this.used.length;i++) this.used[i] = false;
}
 
Example 19
Project: smart-lens   File: TFImageClassifier.java   Source Code and License Vote up 4 votes
/**
 * Classify image.
 *
 * @param bitmap Image to recognize.
 * @return List of top three confidant {@link Recognition}.
 */
@Override
public List<Recognition> scan(Bitmap bitmap) {
    bitmap = Bitmap.createScaledBitmap(bitmap,
            TFImageClassifier.INPUT_SIZE,
            TFImageClassifier.INPUT_SIZE,
            false);
    bitmap.getPixels(mBmpPixelValues,
            0, bitmap.getWidth(),
            0, 0,
            bitmap.getWidth(), bitmap.getHeight());

    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    for (int i = 0; i < mBmpPixelValues.length; ++i) {
        final int val = mBmpPixelValues[i];
        floatValues[i * 3] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
        floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
        floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
    }

    // Copy the input data into TensorFlow.
    mTensorFlowInferenceInterface.feed(
            inputName, floatValues, 1, inputSize, inputSize, 3);

    // Run the inference call.
    mTensorFlowInferenceInterface.run(outputNames);

    // Copy the output Tensor back into the output array.
    mTensorFlowInferenceInterface.fetch(outputName, outputs);

    // Find the best classifications.
    ArrayList<Recognition> recognitions = new ArrayList<>();
    for (int i = 0; i < outputs.length; ++i) {
        if (outputs[i] > THRESHOLD) {
            recognitions.add(new Recognition("" + i, labels.get(i), outputs[i], null));
        }
    }

    //If no match found...
    if (recognitions.size() <= 0) return recognitions;

    //Sort based on the confidence level
    Collections.sort(recognitions, mConfidenceComparator);

    //Return max top 3 results.
    int recognitionsSize = Math.min(recognitions.size(), MAX_RESULTS);
    return recognitions.subList(0, recognitionsSize - 1);
}
 
Example 20
Project: annotation-simulation   File: AnnotationSimulator.java   Source Code and License Vote up 3 votes
public List<ItemId> getRandomSetObjectsAnnotated(int numObjectsToReturn) {

		ArrayList<ItemId> allObjectsAnnotated = new ArrayList<ItemId>(getAllObjectsAnnotated());

		if (numObjectsToReturn > allObjectsAnnotated.size())
			numObjectsToReturn = allObjectsAnnotated.size();

		Collections.shuffle(allObjectsAnnotated, queryModification.getRandomNumberGenerator());

		List<ItemId> sublist = allObjectsAnnotated.subList(0, numObjectsToReturn);
		return sublist;

	}