Java Code Examples for java.util.List#lastIndexOf()

The following examples show how to use java.util.List#lastIndexOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedissonListTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testLastIndexOf1() {
    List<Integer> list = redisson.getList("list");
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);
    list.add(3);
    list.add(7);
    list.add(8);
    list.add(0);
    list.add(10);

    int index = list.lastIndexOf(3);
    Assert.assertEquals(5, index);
}
 
Example 2
Source File: BaseSegListTest.java    From jenetics with Apache License 2.0 6 votes vote down vote up
@Test
public void sliceLastIndexOf() {
	final MSeq<Integer> proxy = MSeq.ofLength(1000);
	for (int i = 0; i < proxy.length(); ++i) {
		proxy.set(i, i);
	}

	final int sliceStart = 50;
	final int sliceEnd = 500;
	final MSeq<Integer> slice = proxy.subSeq(sliceStart, sliceEnd);
	final List<Integer> list = new BaseSeqList<>(slice);

	for (int i = 0; i < list.size(); ++i) {
		final int index = list.lastIndexOf(sliceStart + i);
		Assert.assertEquals(index, i);
	}
}
 
Example 3
Source File: SyntaxDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IPath[] tryResolveKnownSourcePaths(IPath triggerFile, IPath rootPath) {
	List<IPath> sourcePaths = new ArrayList<>();
	IPath relativePath = triggerFile.makeRelativeTo(rootPath).removeTrailingSeparator();
	List<String> segments = Arrays.asList(relativePath.segments());
	int index = segments.lastIndexOf("src");
	if (index >= 0) {
		IPath srcPath = relativePath.removeLastSegments(segments.size() -1 - index);
		IPath container = rootPath.append(srcPath.removeLastSegments(1));
		if (container.append("pom.xml").toFile().exists()
			|| container.append("build.gradle").toFile().exists()) {
			IPath mainJavaPath = container.append("src").append("main").append("java");
			IPath testJavaPath = container.append("src").append("test").append("java");
			if (mainJavaPath.toFile().exists()) {
				sourcePaths.add(mainJavaPath);
			}
			if (testJavaPath.toFile().exists()) {
				sourcePaths.add(testJavaPath);
			}
		}
	}

	return sourcePaths.toArray(new IPath[0]);
}
 
Example 4
Source File: BaseSegListTest.java    From jenetics with Apache License 2.0 6 votes vote down vote up
@Test
public void lastIndexOf() {
	long seed = 12341234;
	final Random random = new Random(seed);

	final MSeq<Long> proxy = MSeq.ofLength(1000);
	for (int i = 0; i < proxy.length(); ++i) {
		proxy.set(i, random.nextLong());
	}

	final List<Long> list = new BaseSeqList<>(proxy);

	random.setSeed(seed);
	for (int i = 0; i < proxy.length(); ++i) {
		final int index = list.lastIndexOf(random.nextLong());
		Assert.assertEquals(index, i);
	}
}
 
Example 5
Source File: ClassPathLoader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
ClassPathLoader addOrReplace(final ClassLoader classLoader) {
  if (ENABLE_TRACE) {
    trace("adding classLoader: " + classLoader);
  }

  List<ClassLoader> classLoadersCopy = new ArrayList<ClassLoader>(this.classLoaders);
  classLoadersCopy.add(0, classLoader);

  // Ensure there is only one instance of this class loader in the list
  ClassLoader removingClassLoader = null;
  int index = classLoadersCopy.lastIndexOf(classLoader);
  if (index != 0) {
    removingClassLoader = classLoadersCopy.get(index);
    if (ENABLE_TRACE) {
      trace("removing previous classLoader: " + removingClassLoader);
    }
    classLoadersCopy.remove(index);
  }

  if (removingClassLoader != null && removingClassLoader instanceof JarClassLoader) {
    ((JarClassLoader) removingClassLoader).cleanUp();
  }

  return new ClassPathLoader(classLoadersCopy, null, this.excludeTCCL);
}
 
Example 6
Source File: AdapterUpdater.java    From EfficientAdapter with Apache License 2.0 6 votes vote down vote up
private int getIndexInPrevious(int indexInNew, T object) {
    int indexInPrevious = mUpdater.indexOf(object);

    if (indexInPrevious > -1 && indexInPrevious < indexInNew) {
        // maybe a duplicate
        List<T> currentObjects = mUpdater.getObjects();
        int lastIndexOf = currentObjects.lastIndexOf(object);
        if (lastIndexOf < indexInNew) {
            // need to insert a new one
            indexInPrevious = -1;
        } else if (lastIndexOf > indexInNew) {
            // another is after, let's take it for now
            indexInPrevious = lastIndexOf;
        } else {
            // same object, same position
            indexInPrevious = indexInNew;
        }
    }
    return indexInPrevious;
}
 
Example 7
Source File: RecursiveOperations.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@ExpectWarning("DMI")
public static void main(String args[]) {
    Set s = new HashSet();
    s.contains(s);
    s.remove(s);
    s.removeAll(s);
    s.retainAll(s);
    s.containsAll(s);

    Map m = new HashMap();
    m.get(m);
    m.remove(m);
    m.containsKey(m);
    m.containsValue(m);

    List lst = new LinkedList();
    lst.indexOf(lst);
    lst.lastIndexOf(lst);

}
 
Example 8
Source File: ClassPathLoader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
ClassPathLoader addOrReplace(final ClassLoader classLoader) {
  if (ENABLE_TRACE) {
    trace("adding classLoader: " + classLoader);
  }

  List<ClassLoader> classLoadersCopy = new ArrayList<ClassLoader>(this.classLoaders);
  classLoadersCopy.add(0, classLoader);

  // Ensure there is only one instance of this class loader in the list
  ClassLoader removingClassLoader = null;
  int index = classLoadersCopy.lastIndexOf(classLoader);
  if (index != 0) {
    removingClassLoader = classLoadersCopy.get(index);
    if (ENABLE_TRACE) {
      trace("removing previous classLoader: " + removingClassLoader);
    }
    classLoadersCopy.remove(index);
  }

  if (removingClassLoader != null && removingClassLoader instanceof JarClassLoader) {
    ((JarClassLoader) removingClassLoader).cleanUp();
  }

  return new ClassPathLoader(classLoadersCopy, null, this.excludeTCCL);
}
 
Example 9
Source File: SearchEverywhereUI.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int getInsertionPoint(SearchEverywhereContributor contributor) {
  if (listElements.isEmpty()) {
    return 0;
  }

  List<SearchEverywhereContributor> list = contributors();
  int index = list.lastIndexOf(contributor);
  if (index >= 0) {
    return isMoreElement(index) ? index : index + 1;
  }

  index = Collections.binarySearch(list, contributor, Comparator.comparingInt(SearchEverywhereContributor::getSortWeight));
  return -index - 1;
}
 
Example 10
Source File: HistoryPlugin.java    From allure2 with Apache License 2.0 5 votes vote down vote up
private boolean isFlaky(final List<HistoryItem> histories) {
    if (histories.size() > 1 && histories.get(0).status == Status.FAILED) {
        final List<Status> statuses = histories.subList(1, histories.size())
                .stream()
                .sorted(comparingByTime())
                .map(HistoryItem::getStatus)
                .collect(Collectors.toList());
        return statuses.indexOf(Status.PASSED) < statuses.lastIndexOf(Status.FAILED)
                && statuses.indexOf(Status.PASSED) != -1;
    }
    return false;
}
 
Example 11
Source File: ReadDescriptors.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void checkDuplicatedByBeansXml(final List<String> list, final List<String> duplicated) {
    for (String str : list) {
        if (list.indexOf(str) != list.lastIndexOf(str)) {
            duplicated.add(str);
        }
    }
}
 
Example 12
Source File: SharedPreferencesPropertyBackend.java    From openlauncher with Apache License 2.0 5 votes vote down vote up
public static void limitListTo(final List<?> list, int maxSize, boolean removeDuplicates) {
    Object o;
    int pos;

    for (int i = 0; removeDuplicates && i < list.size(); i++) {
        o = list.get(i);
        while ((pos = list.lastIndexOf(o)) != i && pos >= 0) {
            list.remove(pos);
        }
    }
    while ((pos = list.size()) > maxSize && pos > 0) {
        list.remove(list.size() - 1);
    }
}
 
Example 13
Source File: SearchEverywhereUI.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int getItemsForContributor(SearchEverywhereContributor<?> contributor) {
  List<SearchEverywhereContributor> contributorsList = contributors();
  int first = contributorsList.indexOf(contributor);
  int last = contributorsList.lastIndexOf(contributor);
  if (isMoreElement(last)) {
    last -= 1;
  }
  return last - first + 1;
}
 
Example 14
Source File: MainActivity.java    From Storm with Apache License 2.0 5 votes vote down vote up
private void addItems(List<AdapterItem> items) {

        if (items == null
                || items.size() == 0) {
            return;
        }

        final List<AdapterItem> current = mAdapter.getItems();

        int index;
        int position;

        for (AdapterItem item: items) {

            // find last index for type
            // insert
            // notify item inserted
            index = current.lastIndexOf(item);
            if (index == -1) {
                // should not happen
                continue;
            }

            position = index + 1;

            current.add(position, item);
            mAdapter.notifyItemInserted(position);
        }
    }
 
Example 15
Source File: BrapiExportActivity.java    From Field-Book with GNU General Public License v2.0 5 votes vote down vote up
private UploadError processResponse(List<NewObservationDbIdsObservations> observationDbIds, List<Observation> observationsNeedingSync) {
    UploadError retVal = UploadError.NONE;
    SimpleDateFormat timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSXXX",
            Locale.getDefault());
    String syncTime = timeStamp.format(Calendar.getInstance().getTime());

    if (observationDbIds.size() != observationsNeedingSync.size()) {
        retVal = UploadError.WRONG_NUM_OBSERVATIONS_RETURNED;
    } else {
        // TODO: update to work with multiple observations per variable
        // Also would be nice to have a cleaner 'find' mechanism
        // For now, just use observationUnitDbId and observationVariableId to key off
        // Won't work for multiple observations of the same variable which we want to support in the future

        for (NewObservationDbIdsObservations observationDbId : observationDbIds) {
            // find observation with matching keys and update observationDbId
            Observation converted = new Observation(observationDbId);
            int first_index = observationsNeedingSync.indexOf(converted);
            int last_index = observationsNeedingSync.lastIndexOf(converted);
            if (first_index == -1) {
                retVal = UploadError.MISSING_OBSERVATION_IN_RESPONSE;
            } else if (first_index != last_index) {
                retVal = UploadError.MULTIPLE_OBSERVATIONS_PER_VARIABLE;
            } else {
                Observation update = observationsNeedingSync.get(first_index);
                update.setDbId(converted.getDbId());
                update.setLastSyncedTime(syncTime);
                observationsNeedingSync.set(first_index, update);
                // TODO: if image data part of observation then store images on BrAPI host
                // a new BrAPI service using the images endpoints is needed
            }
        }

        if (retVal == UploadError.NONE) {
            dataHelper.updateObservations(observationsNeedingSync);
        }
    }

    return retVal;
}
 
Example 16
Source File: RexSimplify.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces the last occurrence of one specified value in a list with
 * another.
 *
 * <p>Does not change the size of the list.
 *
 * <p>Returns whether the value was found.
 */
private static <E> boolean replaceLast(List<E> list, E oldVal, E newVal) {
    final int index = list.lastIndexOf(oldVal);
    if (index < 0) {
        return false;
    }
    list.set(index, newVal);
    return true;
}
 
Example 17
Source File: RulesController.java    From geofence with GNU General Public License v2.0 4 votes vote down vote up
/**
 * On rule priority up.
 *
 * @param event
 *            the event
 */
private void onRulePriorityUp(AppEvent event)
{
    if (tabWidget != null)
    {
        Object tabData = event.getData();

        if (tabData instanceof RuleModel)
        {
            RuleModel model = (RuleModel) tabData;

            RulesTabItem rulesTabItem = (RulesTabItem) tabWidget.getItemByItemId(RULES_TAB_ITEM_ID);
            final RuleGridWidget rulesInfoWidget = rulesTabItem.getRuleManagementWidget().getRulesInfo();
            final Grid<RuleModel> grid = rulesInfoWidget.getGrid();

            List<RuleModel> rules = new ArrayList<RuleModel>(grid.getStore().getModels());
            if (model.getPriority() > 0)
            {
                int indexUp = rules.lastIndexOf(model);
                RuleModel rup = null;
                RuleModel rupup = null;

                rup = ((RuleModel) (rules.get(indexUp)));
                if ((indexUp - 1) >= 0)
                {
                    rupup = ((RuleModel) (rules.get(indexUp - 1)));
                }

                if (rupup != null)
                {
                    rulesManagerServiceRemote.swap(rup.getId(), rupup.getId(),
                        new AsyncCallback<Void>()
                        {

                            public void onFailure(Throwable caught)
                            {

                                Dispatcher.forwardEvent(GeofenceEvents.SEND_ERROR_MESSAGE,
                                    new String[]
                                    {
                                        I18nProvider.getMessages().ruleServiceName(),
                                        I18nProvider.getMessages().ruleFetchFailureMessage()
                                    });
                            }

                            public void onSuccess(Void result)
                            {
                                grid.getStore().getLoader().setSortDir(SortDir.ASC);
                                grid.getStore().getLoader().setSortField(
                                    BeanKeyValue.PRIORITY.getValue());
                                grid.getStore().getLoader().load();

                                Dispatcher.forwardEvent(GeofenceEvents.SEND_INFO_MESSAGE,
                                    new String[]
                                    {
                                        I18nProvider.getMessages().ruleServiceName(),
                                        I18nProvider.getMessages().ruleFetchSuccessMessage()
                                    });
                            }

                        });

                }

            }
        }
    }
}
 
Example 18
Source File: TerminalNodeIteratorTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTerminalNodeListener() {
    String str = "package org.kie.test \n" +
                 "\n" +
                 "rule rule1 when\n" +
                 "then\n" +
                 "end\n" +
                 "rule rule2 when\n" +
                 "then\n" +
                 "end\n" +
                 "rule rule3 when\n" +
                 "    Object()" +
                 "then\n" +
                 "end\n" +
                 "rule rule4 when\n" +
                 "    Object()" +
                 "then\n" +
                 "end\n" +
                 "rule rule5 when\n" + // this will result in two terminal nodes
                 "    Object() or\n" +
                 "    Object()\n" +
                 "then\n" +
                 "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
                  ResourceType.DRL );

    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    List<String> nodes = new ArrayList<String>();
    Iterator it = TerminalNodeIterator.iterator(kbase);
    for ( TerminalNode node = (TerminalNode) it.next(); node != null; node = (TerminalNode) it.next() ) {
        nodes.add( ((RuleTerminalNode) node).getRule().getName() );
    }

    assertEquals( 6,
                  nodes.size() );
    assertTrue( nodes.contains( "rule1" ) );
    assertTrue( nodes.contains( "rule2" ) );
    assertTrue( nodes.contains( "rule3" ) );
    assertTrue( nodes.contains( "rule4" ) );
    assertTrue( nodes.contains( "rule5" ) );

    int first = nodes.indexOf( "rule5" );
    int second = nodes.lastIndexOf( "rule5" );
    assertTrue( first != second );
}
 
Example 19
Source File: StartupUrlArgumentProcessor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
static StartupUrlParser parse(List<String> args,
    String persistedStartupUrl, ILaunchConfiguration config)
    throws CoreException {

  List<String> startupUrls = new ArrayList<String>();

  // Look for "-startupUrl" args
  List<Integer> startupUrlArgIndices = findStartupUrlArgIndices(args);
  for (Integer startupUrlArgIndex : startupUrlArgIndices) {
    String startupUrl = LaunchConfigurationProcessorUtilities.getArgValue(
        args, startupUrlArgIndex + 1);
    if (startupUrl != null) {
      startupUrls.add(startupUrl);
    }
  }

  int gwtShellStyleStartupUrlIndex = -1;
  if (startupUrls.isEmpty()) {
    // Look for GWTShell style startup URL if the other style did not match

    /*
     * Try to find the persisted startup URL in the args. This succeeds in
     * situations when the project configuration is changing (e.g. SDK
     * changes), but fails when the user is changing the value of the
     * startup URL.
     */
    if (!StringUtilities.isEmpty(persistedStartupUrl)) {
      gwtShellStyleStartupUrlIndex = args.lastIndexOf(
          persistedStartupUrl);
    }

    // /* TODO remove
    // * If the above did not work (e.g. user changing value) and the main
    // * type is GWTShell, try to find the last extra arg. This succeeds when
    // * the user is changing values, but can lead to incorrect results when
    // * the project configuration is changing (e.g. SDK changes) since the
    // * last extra arg could be a different type (e.g. module or WAR).
    // * Remember, the block above matches thus preventing this from executing
    // * if the project configuration is changing.
    // */
    // if (gwtShellStyleStartupUrlIndex == -1
    // && GwtLaunchConfigurationProcessorUtilities.isGwtShell(config)) {
    // gwtShellStyleStartupUrlIndex = findStartupUrlFromGwtShellArgs(args);
    // }

    // Assemble the list of startup URLs
    if (gwtShellStyleStartupUrlIndex >= 0) {
      startupUrls.add(args.get(gwtShellStyleStartupUrlIndex));
    }
  }

  return new StartupUrlParser(startupUrls, startupUrlArgIndices,
      gwtShellStyleStartupUrlIndex);
}
 
Example 20
Source File: PurapServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @see org.kuali.kfs.module.purap.document.service.PurapService#addBelowLineItems(org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument)
 */
@Override
@SuppressWarnings("unchecked")
public void addBelowLineItems(PurchasingAccountsPayableDocument document) {
    LOG.debug("addBelowLineItems() started");

    String[] itemTypes = getBelowTheLineForDocument(document);

    List<PurApItem> existingItems = document.getItems();

    List<PurApItem> belowTheLine = new ArrayList<PurApItem>();
    // needed in case they get out of sync below won't work
    sortBelowTheLine(itemTypes, existingItems, belowTheLine);

    List<String> existingItemTypes = new ArrayList<String>();
    for (PurApItem existingItem : existingItems) {
        existingItemTypes.add(existingItem.getItemTypeCode());
    }

    Class itemClass = document.getItemClass();

    for (int i = 0; i < itemTypes.length; i++) {
        int lastFound;
        if (!existingItemTypes.contains(itemTypes[i])) {
            try {
                if (i > 0) {
                    lastFound = existingItemTypes.lastIndexOf(itemTypes[i - 1]) + 1;
                }
                else {
                    lastFound = existingItemTypes.size();
                }
                PurApItem newItem = (PurApItem) itemClass.newInstance();
                newItem.setItemTypeCode(itemTypes[i]);
                newItem.setPurapDocument(document);
                existingItems.add(lastFound, newItem);
                existingItemTypes.add(itemTypes[i]);
            }
            catch (Exception e) {
                // do something
            }
        }
    }

    document.fixItemReferences();
}