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:HSqlManager.java

private static void checkPhage(Connection connection) throws SQLException, IOException {
    List<String[]> all = INSTANCE.readFileAllStrains(INSTANCE.path);
    List<String> clusters = all.stream().map(x -> x[0]).collect(Collectors.toList());
    Set<String> phages = all.stream().map(x -> x[1]).collect(Collectors.toSet());
    List<String> strains = all.stream().map(x -> x[2]).collect(Collectors.toList());
    List<String> phageslist = all.stream().map(x -> x[1]).collect(Collectors.toList());
    Set<String> dbphages = new HashSet<>();
    Statement st = connection.createStatement();
    PreparedStatement insertPhages = connection
            .prepareStatement("INSERT INTO Primerdb.Phages(Name, Cluster, Strain)" + " values(?,?,?);");
    String sql = "SELECT * FROM Primerdb.Phages;";
    ResultSet rs = st.executeQuery(sql);
    while (rs.next()) {
        dbphages.add(rs.getString("Name"));
    }/*  ww w .j av  a2 s.co m*/
    phages.removeAll(dbphages);
    List<String[]> phageinfo = new ArrayList<>();
    if (phages.size() > 0) {
        System.out.println("Phages Added:");
        phages.forEach(x -> {
            String[] ar = new String[3];
            System.out.println(x);
            String cluster = clusters.get(phageslist.indexOf(x));
            String strain = strains.get(phageslist.indexOf(x));
            try {
                insertPhages.setString(1, x);
                insertPhages.setString(2, cluster);
                insertPhages.setString(3, strain);
                insertPhages.addBatch();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                insertPhages.executeBatch();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            ar[0] = x;
            ar[1] = cluster;
            ar[2] = strain;
            phageinfo.add(ar);
        });
        newPhages = phageinfo;
    } else {
        System.out.println("No Phages added");
    }
    st.close();
    insertPhages.close();
}

From source file:gov.nasa.ensemble.core.jscience.csvxml.ProfileLoader.java

private ProfileAndMetadata[] reorderProfilesAndAddMetadata(List<String> headers)
        throws ProfileLoadingException {
    ProfileAndMetadata[] result = new ProfileAndMetadata[headers.size() - ONE_FOR_STARTTIME];
    for (ProfileAndMetadata profileEtc : profileAndMetadataInXmlOrder) {
        String id = profileEtc.getProfile().getId();
        int index = headers.indexOf(id);
        if (index == -1) {
            // already validated, but just in case:
            throw new ProfileLoadingException("No profile id " + id + " listed in CSV headers.");
        } else {/* w ww .ja  v a2  s  .co m*/
            int i = index - ONE_FOR_STARTTIME; // first is always StartTime
            result[i] = profileEtc;
        }
    }
    return result;
}

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

public static String busquedaProfundidad(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;
    String result = "Algoritmo de Busqueda Primero en Profundidad";
    result += "\nCantidad de nodos: " + g.getNodos().size();
    result += "\nCantidad de aristas: " + g.getAristas().size();
    pila.push(inicio);/*from  w w w. ja  v  a2  s .  c  o m*/
    padresPila.push("#");
    while (true) {
        result += "\nPila: " + Arrays.toString(pila.toArray());
        if (pila.isEmpty()) {
            result += "\nNo se encontro el nodo destino";
            break;
        }
        nodoActual = pila.pop();
        nodoPadre = padresPila.pop();
        explorados.add(nodoActual);
        padresExplorados.add(nodoPadre);
        if (nodoActual.equals(fin)) {
            result += "\nNodo destino alcanzado"; //Mostrar camino
            String nodo = nodoActual;
            String secuenciaResultado = "";
            while (nodo != "#") {
                secuenciaResultado = nodo + " " + secuenciaResultado;
                nodo = padresExplorados.get(explorados.indexOf(nodo));
            }
            result += "\nCamino 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);
            }
        }
    }
    return result;
}

From source file:ch.oakmountain.tpa.solver.MacroscopicTopology.java

public void addRoute(List<SystemNode> route) {
    if (route.size() < 2) {
        throw new IllegalArgumentException("A route must containt at least two elements.");
    }//from w  w w.  j  av  a 2  s  . com
    for (int i = 0; i <= route.size() - 2; i++) {
        SystemNode el = route.get(i);
        SystemNode nextEl = route.get(i + 1);
        if (!isLinked(el, nextEl)) {
            throw new IllegalArgumentException("A route must consist of train path sections");
        }
        if (route.indexOf(nextEl) < i + 1) {
            throw new IllegalArgumentException("A route must not be circular");
        }
    }
    routes.add(route);

}

From source file:es.udc.gii.common.eaf.algorithm.operator.reproduction.mutation.de.mutationStrategy.CurrentToRandomMutationStrategy.java

@Override
public Individual getMutatedIndividual(EvolutionaryAlgorithm algorithm, Individual target) {

    List<Individual> individuals, listInd;
    List<Integer> index_list;
    double[] base;
    int n, randomPos;
    double auxGeneValue, x1, x2, x3, x4;
    double F, K;/*from  w  w  w  .j  av  a 2s.c o m*/

    individuals = new ArrayList<>();
    individuals.addAll(algorithm.getPopulation().getIndividuals());

    base = ((Individual) target).getChromosomeAt(0);

    F = this.getFPlugin().get(algorithm);
    K = this.K_plugin.get(algorithm);

    //se eligen los vectores diferenciales:
    listInd = new ArrayList<>();

    index_list = new ArrayList<>();
    index_list.add(individuals.indexOf(target));

    //Se elige el xr3, tiene que ser diferente al target, por eso se hace el do-while:
    do {

        randomPos = EAFRandom.nextInt(individuals.size());

    } while (index_list.contains(randomPos));

    listInd.add(individuals.get(randomPos));
    index_list.add(randomPos);

    for (int i = 0; i < this.getDiffVector() * 2; i++) {

        do {

            randomPos = EAFRandom.nextInt(individuals.size());

        } while (index_list.contains(randomPos));

        listInd.add(individuals.get(randomPos));
        index_list.add(randomPos);

    }

    if (base != null) {
        //Recorremos el numero de genes:
        for (int i = 0; i < base.length; i++) {

            auxGeneValue = base[i];

            for (int j = 0; j < this.getDiffVector(); j += 2) {

                x1 = listInd.get(j + 1).getChromosomeAt(0)[i];
                x2 = listInd.get(j + 2).getChromosomeAt(0)[i];

                auxGeneValue += F * (x1 - x2);

            }

            x3 = listInd.get(0).getChromosomeAt(0)[i];
            x4 = base[i];

            auxGeneValue += K * (x3 - x4);

            base[i] = auxGeneValue;

        }
    }

    Individual mutatedIndividual = new Individual();
    mutatedIndividual.setChromosomeAt(0, base);

    return mutatedIndividual;

}

From source file:com.mec.Services.SuperiorService.java

private List<EstablecimientoPost> buscate() throws IOException {
    Map<String, List<String>> s = superior.getAll();
    List<EstablecimientoPost> list = new ArrayList<>();
    s.forEach((carrera, cueAnexos) -> {
        if (carrera != null && cueAnexos != null) {
            cueAnexos.forEach(cueAnexo -> {
                Integer cue = 0, anexo = 0;
                EstablecimientoPost l = null;
                try {
                    cue = Integer.parseInt(cueAnexo.substring(0, 7));
                    anexo = Integer.parseInt(cueAnexo.substring(8));
                    l = posgreDAO.getByCueAnexo(cue, anexo);

                } catch (Exception e) {

                }//from w ww.  j a va 2 s  .c o  m
                if (l != null) {
                    if (list.contains(l)) {
                        list.get(list.indexOf(l)).getLocalizacion().forEach(loc -> {
                            loc.getOrientacion().add(carrera);
                        });
                    } else {
                        l.getLocalizacion().forEach(loc -> {
                            loc.getOrientacion().add(carrera);
                        });
                        list.add(l);
                    }
                }
            });
        }

    });

    list.forEach(e -> {
        initGeo(e);
    });

    return list;
}

From source file:org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentMgtPostAuthnHandler.java

private List<ClaimMetaData> buildApprovedClaimList(String consentClaimsPrefix,
        Map<String, String[]> requestParams, ConsentClaimsData consentClaimsData) {

    List<ClaimMetaData> approvedClaims = new ArrayList<>();

    for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
        if (entry.getKey().startsWith(consentClaimsPrefix)) {
            String claimId = entry.getKey().substring(consentClaimsPrefix.length());

            ClaimMetaData consentClaim = new ClaimMetaData();

            try {
                consentClaim.setId(Integer.parseInt(claimId));
            } catch (NumberFormatException e) {
                // Invalid consent claim input. Ignore.
                continue;
            }/*w  w w.j  a  va 2s .  c  o m*/
            List<ClaimMetaData> mandatoryClaims = consentClaimsData.getMandatoryClaims();

            int claimIndex = mandatoryClaims.indexOf(consentClaim);
            if (claimIndex != -1) {
                approvedClaims.add(mandatoryClaims.get(claimIndex));
            }

            List<ClaimMetaData> requestedClaims = consentClaimsData.getRequestedClaims();
            claimIndex = requestedClaims.indexOf(consentClaim);
            if (claimIndex != -1) {
                approvedClaims.add(requestedClaims.get(claimIndex));
            }
        }
    }
    return approvedClaims;
}

From source file:com.lixiaocong.social.MyJdbcConnection.java

public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }/* ww w.  j a  v  a  2 s.  c  om*/
    StringBuilder providerUsersCriteriaSql = new StringBuilder();
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("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();
        providerUsersCriteriaSql.append("providerId = :providerId_").append(providerId)
                .append(" and providerUserId in (:providerUserIds_").append(providerId).append(")");
        parameters.addValue("providerId_" + providerId, providerId);
        parameters.addValue("providerUserIds_" + providerId, entry.getValue());
        if (it.hasNext()) {
            providerUsersCriteriaSql.append(" or ");
        }
    }
    List<Connection<?>> resultList = new NamedParameterJdbcTemplate(jdbcTemplate)
            .query(selectFromUserConnection() + " where userId = :userId and " + providerUsersCriteriaSql
                    + " order by providerId, rank", parameters, connectionMapper);
    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:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

private void parseField(List<String> fieldNames, List<Primitive> fieldTypes, Row.RowBuilder rowBuilder,
        JsonParser parser) throws IOException {
    final String fieldName = parser.getCurrentName();

    // Move to next token, which is name's value
    JsonToken token = parser.nextToken();
    int i = fieldNames.indexOf(fieldName);
    if (i < 0) {
        return;/*from   ww w . j a  v a2 s  .  c o m*/
    }
    switch (token) {
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
        Primitive type = fieldTypes.get(i);
        if (type == null) {
            if (token == JsonToken.VALUE_NUMBER_INT) {
                type = Primitive.INT;
            } else {
                type = Primitive.FLOAT;
            }
        }
        switch (type) {
        case BYTE:
            rowBuilder.set(i, parser.getIntValue());
            break;
        case SHORT:
            rowBuilder.set(i, parser.getShortValue());
            break;
        case INT:
            rowBuilder.set(i, parser.getIntValue());
            break;
        case LONG:
            rowBuilder.set(i, parser.getLongValue());
            break;
        case FLOAT:
            rowBuilder.set(i, parser.getFloatValue());
            break;
        case DOUBLE:
            rowBuilder.set(i, parser.getDoubleValue());
            break;
        }
        break;
    case VALUE_TRUE:
        rowBuilder.set(i, true);
        break;
    case VALUE_FALSE:
        rowBuilder.set(i, false);
        break;
    case VALUE_NULL:
        break;
    default:
        rowBuilder.set(i, parser.getText());
    }
}

From source file:com.google.gdt.eclipse.designer.mobile.preferences.device.DevicesPreferencePage.java

/**
 * Configures DND in {@link #m_viewer}./*from  ww  w  . ja v  a2  s. co m*/
 */
private void configureDND() {
    Transfer[] transfers = new Transfer[] { EmptyTransfer.INSTANCE };
    m_viewer.addDragSupport(DND.DROP_MOVE, transfers, new DragSourceListener() {
        public void dragStart(DragSourceEvent event) {
            m_dragElements = getSelectedElements();
            m_dragCategory = m_dragElements.get(0) instanceof CategoryInfo;
            // check that we drag only categories or only entries
            for (Object element : m_dragElements) {
                if (m_dragCategory != element instanceof CategoryInfo) {
                    event.doit = false;
                }
            }
        }

        public void dragSetData(DragSourceEvent event) {
        }

        public void dragFinished(DragSourceEvent event) {
        }
    });
    ViewerDropAdapter dropAdapter = new ViewerDropAdapter(m_viewer) {
        @Override
        protected int determineLocation(DropTargetEvent event) {
            if (event.item instanceof Item) {
                Item item = (Item) event.item;
                Point coordinates = m_viewer.getControl().toControl(event.x, event.y);
                Rectangle bounds = getBounds(item);
                // when drag device, relation with category can be only ON
                if (!m_dragCategory && determineTarget(event) instanceof CategoryInfo) {
                    return LOCATION_ON;
                }
                // in all other cases, drop before/after
                return coordinates.y < bounds.y + bounds.height / 2 ? LOCATION_BEFORE : LOCATION_AFTER;
            }
            return LOCATION_NONE;
        }

        @Override
        public boolean validateDrop(Object target, int operation, TransferData transferType) {
            // category can be dragged only relative other category
            if (m_dragCategory) {
                return target instanceof CategoryInfo;
            }
            // all other cases are valid
            return true;
        }

        @Override
        public boolean performDrop(Object data) {
            Object target = getCurrentTarget();
            int location = getCurrentLocation();
            if (m_dragCategory) {
                Assert.instanceOf(CategoryInfo.class, target);
                Assert.isTrue(location == LOCATION_BEFORE || location == LOCATION_AFTER);
                // prepare next category
                CategoryInfo nextCategory;
                {
                    List<CategoryInfo> categories = DeviceManager.getCategories();
                    int index = categories.indexOf(target);
                    if (location == LOCATION_BEFORE) {
                        nextCategory = categories.get(index);
                    } else {
                        nextCategory = GenericsUtils.getNextOrNull(categories, index);
                    }
                }
                // add commands
                for (Object element : m_dragElements) {
                    CategoryInfo category = (CategoryInfo) element;
                    commands_add(new CategoryMoveCommand(category, nextCategory));
                }
            } else if (target instanceof CategoryInfo) {
                Assert.isTrue(location == LOCATION_ON);
                CategoryInfo targetCategory = (CategoryInfo) target;
                for (Object element : m_dragElements) {
                    DeviceInfo device = (DeviceInfo) element;
                    commands_add(new DeviceMoveCommand(device, targetCategory, null));
                }
            } else {
                DeviceInfo targetDevice = (DeviceInfo) target;
                CategoryInfo targetCategory = targetDevice.getCategory();
                // prepare next device
                DeviceInfo nextDevice;
                {
                    List<DeviceInfo> entries = targetCategory.getDevices();
                    int index = entries.indexOf(targetDevice);
                    if (location == LOCATION_BEFORE) {
                        nextDevice = entries.get(index);
                    } else {
                        nextDevice = GenericsUtils.getNextOrNull(entries, index);
                    }
                }
                // add commands
                for (Object element : m_dragElements) {
                    DeviceInfo device = (DeviceInfo) element;
                    commands_add(new DeviceMoveCommand(device, targetCategory, nextDevice));
                }
            }
            // refresh viewer to show result of applying commands
            refreshViewer();
            return true;
        }
    };
    dropAdapter.setScrollExpandEnabled(false);
    m_viewer.addDropSupport(DND.DROP_MOVE, transfers, dropAdapter);
}