Example usage for java.util LinkedList LinkedList

List of usage examples for java.util LinkedList LinkedList

Introduction

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

Prototype

public LinkedList() 

Source Link

Document

Constructs an empty list.

Usage

From source file:Main.java

public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> aClazz) {
    //Check class hierarchy
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        T anno = c.getAnnotation(aClazz);
        if (anno != null) {
            return anno;
        }/*from   ww w  .  ja  v a 2  s.  c o m*/
    }

    //Check interfaces (breadth first)
    Queue<Class<?>> q = new LinkedList<Class<?>>();
    q.add(clazz);
    while (!q.isEmpty()) {
        Class<?> c = q.remove();
        if (c != null) {
            if (c.isInterface()) {
                T anno = c.getAnnotation(aClazz);
                if (anno != null) {
                    return anno;
                }
            } else {
                q.add(c.getSuperclass());
            }
            q.addAll(Arrays.asList(c.getInterfaces()));
        }
    }

    return null;
}

From source file:Main.java

/**
 * <strong>WARNING:</strong> very low efficiency (O(N*N))
 * @return A list containing the elements of source that are not in filter, using <code>equivalence</code> to distinguish different elements.
 *//*  ww w  .  ja  v a 2s  .c  o m*/
public static <T> List<T> difference(Iterable<? extends T> source, Iterable<? extends T> filter,
        Equivalence<? super T> equivalence) {
    final List<T> result = new LinkedList<T>();
    if (source != null && filter != null) {
        sourceLoop: for (T sourceElement : source) {
            for (T filterElement : filter) {
                if (equivalence.equivalent(sourceElement, filterElement)) {
                    continue sourceLoop;
                }
            }
            result.add(sourceElement);
        }
    } else if (source != null && filter == null) {
        Iterables.addAll(result, source);
    }
    return result;
}

From source file:Main.java

/**
 * Returns an array of all methods in a class with the specified parameter types.
 *
 * The return type is optional, it will not be compared if it is {@code null}.
 * Use {@code void.class} if you want to search for methods returning nothing.
 *//*w w w  .ja v a  2s  .co m*/
public static Method[] findMethodsByExactParameters(Class<?> clazz, Class<?> returnType,
        Class<?>... parameterTypes) {
    List<Method> result = new LinkedList<Method>();
    for (Method method : clazz.getDeclaredMethods()) {
        if (returnType != null && returnType != method.getReturnType())
            continue;

        Class<?>[] methodParameterTypes = method.getParameterTypes();
        if (parameterTypes.length != methodParameterTypes.length)
            continue;

        boolean match = true;
        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameterTypes[i] != methodParameterTypes[i]) {
                match = false;
                break;
            }
        }

        if (!match)
            continue;

        method.setAccessible(true);
        result.add(method);
    }
    return result.toArray(new Method[result.size()]);
}

From source file:Main.java

/**
 * Generate a hash chain of a random number
 * @param r1//from   www  . ja  v a 2s .c o m
 * @param numHash
 * @return
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 */
public static LinkedList<BigInteger> getHashChain(BigInteger r1, int numHash)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {

    LinkedList<BigInteger> hashChain = new LinkedList<BigInteger>();
    hashChain.add(r1);

    for (int i = 1; i < numHash; i++) {
        byte[] lastR = hashChain.getLast().toByteArray();
        hashChain.add(new BigInteger(1, SHA1(lastR)));
    }

    return hashChain;
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }//from ww w  .j ava  2 s  . com

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:edu.csun.ecs.cs.multitouchj.application.whiteboard.Whiteboard.java

public static void main(String[] args) {
    LinkedList<String> arguments = new LinkedList<String>();
    for (String argument : args) {
        arguments.add(argument);//from  ww w.java  2  s. com
    }

    TreeMap<String, String> parameters = new TreeMap<String, String>();
    if (arguments.contains("-ix")) {
        parameters.put(ObjectObserverMoteJ.Parameter.InverseX.toString(), "");
    }
    if (arguments.contains("-iy")) {
        parameters.put(ObjectObserverMoteJ.Parameter.InverseY.toString(), "");
    }

    Whiteboard whiteboard = new Whiteboard();
    whiteboard.run(parameters);
}

From source file:Main.java

public static Collection invokeForEach(Collection in, String methodName, Object[] args)
        throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    Iterator<Object> it = in.iterator();

    Class[] argsClasses = new Class[args.length];
    for (int i = 0; i < args.length; i++)
        argsClasses[i] = args[i].getClass();

    LinkedList<Object> out = new LinkedList<Object>();

    while (it.hasNext()) {
        Object obj = it.next();//from   w  ww  .  j  a v a 2 s  . com

        Method m = obj.getClass().getMethod(methodName, argsClasses);
        Object value2 = m.invoke(obj, args);
        out.add(value2);

    }
    return out;
}

From source file:Main.java

/*******
 * It is easy to accidentally create GStrings instead of String in a groovy file. This will auto correct the problem
 * for byon node definitions by calling the toString() methods for map keys and values.
 *
 * @param originalNodesList/*from  www .j a  v  a2  s . c o m*/
 *            .
 * @return the
 */
public static List<Map<String, String>> convertToStringMap(final List<Map<Object, Object>> originalNodesList) {
    List<Map<String, String>> nodesList;
    nodesList = new LinkedList<Map<String, String>>();

    for (final Map<Object, Object> originalMap : originalNodesList) {
        final Map<String, String> newMap = new LinkedHashMap<String, String>();
        final Set<Entry<Object, Object>> entries = originalMap.entrySet();
        for (final Entry<Object, Object> entry : entries) {
            newMap.put(entry.getKey().toString(), entry.getValue().toString());
        }
        nodesList.add(newMap);

    }
    return nodesList;
}

From source file:Main.java

/**
 * Adds the value to map. If the key does not exists new value list is created and the value is
 * added to it/*w w w  .j a v  a  2  s . c o m*/
 * 
 * @param <K>
 *            the key type
 * @param <V>
 *            the value type
 * @param map
 *            the map
 * @param key
 *            the key
 * @param newValue
 *            the new value
 */
public static <K, V> void addValueToMap(Map<K, List<V>> map, K key, V newValue) {
    List<V> list = map.get(key);
    if (list == null) {
        list = new LinkedList<V>();
        map.put(key, list);
    }
    list.add(newValue);
}

From source file:Main.java

public static Element[] getChildrenByName(Element e, String name) {
    NodeList nl = e.getChildNodes();
    int max = nl.getLength();
    LinkedList<Node> list = new LinkedList<Node>();
    for (int i = 0; i < max; i++) {
        Node n = nl.item(i);/*from   w w w. j a va 2 s.  com*/
        if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) {
            list.add(n);
        }
    }
    return list.toArray(new Element[list.size()]);
}