java.util.List#lastIndexOf ( )源码实例Demo

下面列出了java.util.List#lastIndexOf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jenetics   文件: BaseSegListTest.java
@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);
	}
}
 
源代码2 项目: jenetics   文件: BaseSegListTest.java
@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);
	}
}
 
源代码3 项目: gemfirexd-oss   文件: ClassPathLoader.java
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);
}
 
源代码4 项目: EfficientAdapter   文件: AdapterUpdater.java
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;
}
 
源代码5 项目: spotbugs   文件: RecursiveOperations.java
@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);

}
 
源代码6 项目: gemfirexd-oss   文件: ClassPathLoader.java
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);
}
 
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]);
}
 
源代码8 项目: redisson   文件: RedissonListTest.java
@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);
}
 
源代码9 项目: Bats   文件: RexSimplify.java
/**
 * 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;
}
 
源代码10 项目: consulo   文件: SearchEverywhereUI.java
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;
}
 
源代码11 项目: Field-Book   文件: BrapiExportActivity.java
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;
}
 
源代码12 项目: Storm   文件: MainActivity.java
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);
        }
    }
 
源代码13 项目: consulo   文件: SearchEverywhereUI.java
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;
}
 
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);
    }
}
 
源代码15 项目: tomee   文件: ReadDescriptors.java
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);
        }
    }
}
 
源代码16 项目: allure2   文件: HistoryPlugin.java
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;
}
 
源代码17 项目: kogito-runtimes   文件: TerminalNodeIteratorTest.java
@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 );
}
 
源代码18 项目: geofence   文件: RulesController.java
/**
 * 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()
                                    });
                            }

                        });

                }

            }
        }
    }
}
 
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);
}
 
源代码20 项目: kfs   文件: PurapServiceImpl.java
/**
 * @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();
}