Example usage for java.util List indexOf

List of usage examples for java.util List indexOf

Introduction

In this page you can find the example usage for java.util List indexOf.

Prototype

int indexOf(Object o);

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:com.core.controller.AlgoritmoController.java

public static Solucion busquedaProfundidadConSolucion(Grafo g, String inicio, String fin) {
    Deque<String> pila = new ArrayDeque<>();
    Deque<String> padresPila = new ArrayDeque<>();
    List<String> explorados = new ArrayList<>();
    List<String> padresExplorados = new ArrayList<>();
    String nodoActual, nodoPadre;
    Solucion result = new Solucion("Algoritmo de Busqueda Primero en Profundidad");
    result.agregarPaso("Cantidad de nodos: " + g.getNodos().size());
    result.agregarPaso("Cantidad de aristas: " + g.getAristas().size());
    pila.push(inicio);/*  w w w.  j  a v a 2  s .c o  m*/
    padresPila.push("#");
    while (true) {
        result.agregarPaso("Pila: " + Arrays.toString(pila.toArray()));
        if (pila.isEmpty()) {
            result.agregarPaso("No se encontro el nodo destino");
            break;
        }
        nodoActual = pila.pop();
        nodoPadre = padresPila.pop();
        explorados.add(nodoActual);
        padresExplorados.add(nodoPadre);
        if (nodoActual.equals(fin)) {
            result.agregarPaso("Nodo fin alcanzado"); //Mostrar camino
            String nodo = nodoActual;
            String secuenciaResultado = "";
            while (nodo != "#") {
                secuenciaResultado = nodo + " " + secuenciaResultado;
                nodo = padresExplorados.get(explorados.indexOf(nodo));
            }
            result.agregarPaso("Camino solucion: " + secuenciaResultado);
            break;
        }
        List<String> vecinos = g.nodosVecinos(nodoActual);
        for (int i = vecinos.size() - 1; i >= 0; i--) {
            String a = vecinos.get(i);
            if (!explorados.contains(a)) {
                if (pila.contains(a)) {
                    pila.remove(a);
                    padresPila.remove(nodoActual);
                }
                pila.push(a);
                padresPila.push(nodoActual);
            }
        }
    }
    //Verifico la solucion y la guardo en Solucion
    if (result.getPasos().contains("Nodo fin alcanzado")) {
        String solucion = result.getPasos().split("Nodo fin alcanzado\n")[1];
        System.out.println("Solucion: " + solucion);
        String[] array = solucion.split(" ");
        //            ArrayUtils.reverse(array);
        for (String nombreNodo : array) {
            System.out.println("--------------------------------------");
            for (Map.Entry<String, Nodo> n : g.getNodos().entrySet()) {
                System.out.println("Comparando " + n.getKey() + " con " + nombreNodo);
                if (n.getKey().equals(nombreNodo)) {
                    System.out.println("Son iguales! Agregando " + nombreNodo + " a la lista");
                    result.getNodos().add(n.getValue());
                }
            }
        }

        System.out.println(
                "Nodos del resultado final en la lista: " + Arrays.toString(result.getNodos().toArray()));
    }
    return result;
}

From source file:com.antsdb.saltedfish.sql.mysql.Insert_stmtGenerator.java

private Instruction gen(GeneratorContext ctx, ObjectName tableName, Insert_stmt_valuesContext rule,
        boolean ignoreError) {
    // collect column names

    TableMeta table = Checks.tableExist(ctx.getSession(), tableName);
    tableName = table.getObjectName();//w  ww  .j a  va 2s  .  c o  m
    List<ColumnMeta> fields = new ArrayList<ColumnMeta>();
    if (rule.insert_stmt_values_columns() != null) {
        for (Column_nameContext i : rule.insert_stmt_values_columns().column_name()) {
            String columnName = Utils.getIdentifier(i.identifier());
            ColumnMeta iii = Checks.columnExist(table, columnName);
            fields.add(iii);
        }
    } else {
        fields.addAll(table.getColumns());
    }

    // auto increment column

    List<Operator> defaultValues = new ArrayList<>();
    ColumnMeta autoIncrement = table.findAutoIncrementColumn();
    int posAutoIncrement = -1;
    if (autoIncrement != null) {
        posAutoIncrement = fields.indexOf(autoIncrement);
        if (posAutoIncrement < 0) {
            fields.add(autoIncrement);
            defaultValues.add(new OpIncrementColumnValue(table, null));
        }
    }

    // columns with default value

    for (ColumnMeta i : table.getColumns()) {
        if (i.getDefault() == null) {
            continue;
        }
        if (fields.contains(i)) {
            continue;
        }
        Operator expr = ExprGenerator.gen(ctx, null, i.getDefault());
        fields.add(i);
        defaultValues.add(expr);
    }

    // collect expressions

    List<List<Operator>> rows = new ArrayList<>();
    for (Insert_stmt_values_rowContext i : rule.insert_stmt_values_row()) {
        List<Operator> values = new ArrayList<>();
        for (ExprContext j : i.expr()) {
            Operator jj = ExprGenerator.gen(ctx, null, j);
            if (values.size() == posAutoIncrement) {
                jj = new OpIncrementColumnValue(table, jj);
            }
            values.add(jj);
        }
        values.addAll(defaultValues);
        if (fields.size() != values.size()) {
            throw new OrcaException("number of columns is not matching number of values");
        }

        // auto casting according to column data type

        Utils.applyCasting(fields, values);

        // end

        rows.add(values);
    }

    // all set

    GTable gtable = ctx.getGtable(tableName);
    InsertSingleRow insert = new InsertSingleRow(ctx.getOrca(), table, gtable, fields, rows);
    insert.setIgnoreError(ignoreError);
    return insert;
}

From source file:io.github.davejoyce.dao.composite.social.connect.jpa.JpaConnectionRepository.java

/**
 * {@inheritDoc}// w ww  .j a  va2  s  .  c om
 */
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }
    StringBuilder providerUsersCriteriaJpaQl = new StringBuilder(QUERY_SELECT_FROM)
            .append("WHERE ausc.key.appUser.userId = :userId").append(" AND ");
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        providerUsersCriteriaJpaQl.append("ausc.key.providerId = :providerId_").append(providerId)
                .append("AND ausc.key.providerUserId IN (:providerUserIds_").append(providerId).append(")");
        if (it.hasNext()) {
            providerUsersCriteriaJpaQl.append(" OR ");
        }
    }
    providerUsersCriteriaJpaQl.append(" ORDER BY ausc.key.providerId, ausc.rank");
    TypedQuery<AppUserSocialConnection> query = entityManager
            .createQuery(providerUsersCriteriaJpaQl.toString(), AppUserSocialConnection.class)
            .setParameter("userId", userId);
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        query.setParameter(("providerId_" + providerId), providerId)
                .setParameter(("providerUserIds_" + providerId), entry.getValue());
    }
    List<Connection<?>> resultList = appUserSocialConnectionsToConnections(query.getResultList());
    MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>();
    for (Connection<?> connection : resultList) {
        String providerId = connection.getKey().getProviderId();
        List<String> userIds = providerUsers.get(providerId);
        List<Connection<?>> connections = connectionsForUsers.get(providerId);
        if (connections == null) {
            connections = new ArrayList<Connection<?>>(userIds.size());
            for (int i = 0; i < userIds.size(); i++) {
                connections.add(null);
            }
            connectionsForUsers.put(providerId, connections);
        }
        String providerUserId = connection.getKey().getProviderUserId();
        int connectionIndex = userIds.indexOf(providerUserId);
        connections.set(connectionIndex, connection);
    }
    return connectionsForUsers;
}

From source file:org.powertac.du.DefaultBrokerService.java

/**
 * Called by initialization service once at the beginning of each game.
 * Configures parameters, sets up and publishes default tariffs.
 *//*  w ww .j av  a  2s. c  o  m*/
@Override
public String initialize(Competition competition, List<String> completedInits) {
    // defer for TariffMarket initialization
    int index = completedInits.indexOf("TariffMarket");
    if (index == -1) {
        return null;
    }

    // log in to ccs
    competitionControlService.loginBroker(face.getUsername());

    // set up local state
    bootstrapMode = competitionControlService.isBootstrapMode();
    log.info("init, bootstrapMode=" + bootstrapMode);
    customerSubscriptions = new HashMap<TariffSpecification, HashMap<CustomerInfo, CustomerRecord>>();
    lastOrder = new HashMap<Timeslot, Order>();
    randomSeed = randomSeedRepo.getRandomSeed(this.getClass().getName(), 0, "pricing");

    // if we are in bootstrap mode, we need to set up the dataset
    if (bootstrapMode) {
        //netUsageMap = new HashMap<CustomerInfo, ArrayList<Double>>();
        marketTxMap = new HashMap<Timeslot, ArrayList<MarketTransaction>>();
        marketMWh = new ArrayList<Double>();
        marketPrice = new ArrayList<Double>();
        weather = new ArrayList<WeatherReport>();
    }

    // pull down configuration
    serverPropertiesService.configureMe(this);

    // create and publish default tariffs
    defaultConsumption = new TariffSpecification(face, PowerType.CONSUMPTION)
            .addRate(new Rate().withValue(defaultConsumptionRate));
    tariffMarketService.setDefaultTariff(defaultConsumption);
    customerSubscriptions.put(defaultConsumption, new HashMap<CustomerInfo, CustomerRecord>());

    defaultInterruptibleConsumption = new TariffSpecification(face, PowerType.INTERRUPTIBLE_CONSUMPTION)
            .addRate(new Rate().withValue(defaultConsumptionRate));
    tariffMarketService.setDefaultTariff(defaultInterruptibleConsumption);
    customerSubscriptions.put(defaultInterruptibleConsumption, new HashMap<CustomerInfo, CustomerRecord>());

    defaultProduction = new TariffSpecification(face, PowerType.PRODUCTION)
            .addRate(new Rate().withValue(defaultProductionRate));
    tariffMarketService.setDefaultTariff(defaultProduction);
    customerSubscriptions.put(defaultProduction, new HashMap<CustomerInfo, CustomerRecord>());

    return "DefaultBroker";
}

From source file:it.drwolf.ridire.index.sketch.SketchDifferenceManager.java

private List<SketchDiff> computeSketchDifference(List<SketchTable> firstLemmaSketchTables,
        List<SketchTable> secondLemmaSketchTables) {
    List<SketchDiff> sketchDiffs = new ArrayList<SketchDiff>();
    for (SketchTable st1 : firstLemmaSketchTables) {
        if (st1.getSketchName().startsWith("NONE")) {
            continue;
        }//w  ww .j  a v  a 2 s. co  m
        for (SketchTable st2 : secondLemmaSketchTables) {
            if (st2.getSketchName().startsWith("NONE")) {
                continue;
            }
            if (st1.getSketchName().equals(st2.getSketchName())) {
                List<SketchDiffRow> diffRows = new ArrayList<SketchDiffRow>();
                List<SketchResultRow> firstRows = st1.getRows();
                List<SketchResultRow> secondRows = st2.getRows();
                for (SketchResultRow r1 : firstRows) {
                    int indexOfR1 = secondRows.indexOf(r1);
                    SketchResultRow r2 = null;
                    if (indexOfR1 >= 0) {
                        r2 = secondRows.get(indexOfR1);
                    }
                    SketchDiffRow computedDiff = this.computeDiff(r1, r2);
                    // if (computedDiff.getFrequency1() > 2
                    // || computedDiff.getFrequency2() > 2) {
                    diffRows.add(computedDiff);
                    // }
                }
                for (SketchResultRow r2 : secondRows) {
                    if (firstRows.contains(r2)) {
                        continue;
                    }
                    SketchDiffRow computedDiff = this.computeDiff(null, r2);
                    // if (computedDiff.getFrequency1() > 5
                    // || computedDiff.getFrequency2() > 5) {
                    diffRows.add(computedDiff);
                    // }
                }
                Collections.sort(diffRows, new SketchDiffSummComparator());
                diffRows = diffRows.subList(0, Math.min(25, diffRows.size()));
                Collections.sort(diffRows);
                if (diffRows.size() > 0) {
                    SketchDiff sd = new SketchDiff(st1.getSketchName());
                    sd.setRows(diffRows);
                    sketchDiffs.add(sd);
                }
            }
        }
    }
    return sketchDiffs;
}

From source file:org.jasig.portlet.contacts.control.PortletViewController.java

@ModelAttribute("domains")
public Set<ContactDomain> getDomains(PortletPreferences prefs) {
    log.debug("finding Domains to return");
    final List<String> domainActive = Arrays.asList(prefs.getValues("domainsActive", new String[0]));

    String[] defaultOn = prefs.getValues("defaultOn", new String[0]);
    String[] userOn = prefs.getValues("domainOn", new String[0]);
    String[] userOff = prefs.getValues("domainOff", new String[0]);

    Set<String> domains = new HashSet<String>();
    domains.addAll(Arrays.asList(defaultOn));
    domains.addAll(Arrays.asList(userOn));
    domains.removeAll(Arrays.asList(userOff));
    domains.retainAll(domainActive);//  w  w  w .  j  a  v  a2 s  .c o  m

    Set<ContactDomain> activeDomains = new TreeSet<ContactDomain>(new Comparator<ContactDomain>() {

        @Override
        public int compare(ContactDomain o1, ContactDomain o2) {
            int index1 = domainActive.indexOf(o1.getName());
            int index2 = domainActive.indexOf(o2.getName());
            return index1 - index2;
        }
    });
    for (ContactDomain domain : contactDomains) {
        if (domains.contains(domain.getName())) {
            activeDomains.add(domain);
        }
    }
    log.debug("returning " + activeDomains.size() + "domains");
    return activeDomains;
}

From source file:com.activiti.web.rest.client.DisplayJsonClientResource.java

protected List<String> gatherCompletedFlows(List<String> completedActivityInstances,
        List<String> currentActivityinstances, BpmnModel pojoModel) {

    List<String> completedFlows = new ArrayList<String>();
    List<String> activities = new ArrayList<String>(completedActivityInstances);
    activities.addAll(currentActivityinstances);

    // TODO: not a robust way of checking when parallel paths are active, should be revisited
    // Go over all activities and check if it's possible to match any outgoing paths against the activities
    for (FlowElement activity : pojoModel.getMainProcess().getFlowElements()) {
        if (activity instanceof FlowNode) {
            int index = activities.indexOf(activity.getId());
            if (index >= 0 && index + 1 < activities.size()) {
                List<SequenceFlow> outgoingFlows = ((FlowNode) activity).getOutgoingFlows();
                for (SequenceFlow flow : outgoingFlows) {
                    String destinationFlowId = flow.getTargetRef();
                    if (destinationFlowId.equals(activities.get(index + 1))) {
                        completedFlows.add(flow.getId());
                    }//from   ww  w .j  av  a 2 s .co  m
                }
            }
        }
    }
    return completedFlows;
}

From source file:com.springrts.springls.statistics.Statistics.java

/**
 * Returns the list of mods being played right now (top 5 mods only)
 * with frequencies (number of battles).
 * @return [list-len] "modname1" [numBattles1] "modname2" [numBattles2]" ...
 *   Where delimiter is TAB (not SPACE).
 *   An empty list is denoted by 0 value for list-len.
 *///from  w w  w  . j  a  v a 2 s. com
private String currentlyPopularModsList() {

    List<ModBattles> modBattles = new ArrayList<ModBattles>();

    for (int i = 0; i < context.getBattles().getBattlesSize(); i++) {
        Battle battle = context.getBattles().getBattleByIndex(i);
        if (battle.inGame() && (battle.getClientsSize() >= 1)) {
            // add to list or update in list:

            int modIndex = modBattles.indexOf(battle.getModName());
            if (modIndex == -1) {
                modBattles.add(new ModBattles(battle.getModName(), 1));
            } else {
                modBattles.get(modIndex).addBattles(1);
            }
        }
    }

    return createModPopularityString(modBattles);
}

From source file:com.evolveum.midpoint.web.component.prism.PrismValuePanel.java

private boolean isAddButtonVisible() {
    Component inputPanel = this.get(ID_VALUE_CONTAINER).get(ID_INPUT);
    ValueWrapper valueWrapper = model.getObject();

    if (valueWrapper.isReadonly()) {
        return false;
    }//from  w  ww .ja va  2s . com

    ItemWrapper propertyWrapper = valueWrapper.getItem();
    Item property = propertyWrapper.getItem();

    ItemDefinition definition = property.getDefinition();
    int max = definition.getMaxOccurs();
    List<ValueWrapper> usableValues = getUsableValues(propertyWrapper);
    if (usableValues.indexOf(valueWrapper) != usableValues.size() - 1) {
        return false;
    }

    if (max == -1) {
        return true;
    }

    if (countNonDeletedValues(propertyWrapper) >= max) {
        return false;
    }

    return isAccessible(definition, propertyWrapper.getContainer().getObject().getStatus());
}

From source file:com.tobedevoured.naether.NaetherTest.java

@Test
public void resolveNaetherDependencies() throws Exception {
    Project mavenProject = new Project("pom.xml");

    assertEquals("core", mavenProject.getArtifactId());

    naether.addDependencies(mavenProject);

    naether.resolveDependencies();//  w  ww  . ja va2s .  c o m

    for (Dependency dependency : naether.getDependencies()) {
        String notation = Notation.generate(dependency);
        log.debug("Dependency: {} {}", notation, dependency.getScope());
    }

    List<String> completeDeps = Bootstrap.DEPENDENCIES;

    assertEquals(completeDeps.size(), naether.getDependenciesNotation().size());

    List<String> missingDeps = new ArrayList<String>();
    for (String dep : naether.getDependenciesNotation()) {
        if (completeDeps.indexOf(dep) == -1) {
            missingDeps.add(dep);
        }
    }

    if (missingDeps.size() > 0) {
        LoggerFactory.getLogger(this.getClass()).warn("Resolved Deps: {}", naether.getDependenciesNotation());
        fail("Missing Dependencies: " + missingDeps);
    }

}