Example usage for java.util LinkedList remove

List of usage examples for java.util LinkedList remove

Introduction

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

Prototype

public E remove(int index) 

Source Link

Document

Removes the element at the specified position in this list.

Usage

From source file:Main.java

public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();

    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");

    System.out.println(lList);/*from w  w  w .ja  va 2  s.  c om*/
    System.out.println(lList.remove("2"));
    System.out.println(lList);
    Object obj = lList.remove(2);
    System.out.println(obj + " has been removed from LinkedList");
    System.out.println(lList);
}

From source file:ubic.gemma.core.apps.GemmaCLI.java

public static void main(String[] args) {

    /*//  w w w.ja va 2s  .c  o m
     * Build a map from command names to classes.
     */
    Map<CommandGroup, Map<String, String>> commands = new HashMap<>();
    Map<String, Class<? extends AbstractCLI>> commandClasses = new HashMap<>();
    try {

        final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
                false);
        provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

        // searching entire hierarchy is 1) slow and 2) generates annoying logging from static initialization code.
        final Set<BeanDefinition> classes = provider.findCandidateComponents("ubic.gemma.core.apps");
        classes.addAll(provider.findCandidateComponents("ubic.gemma.core.loader.association.phenotype"));

        for (BeanDefinition bean : classes) {
            try {
                @SuppressWarnings("unchecked")
                Class<? extends AbstractCLI> aClazz = (Class<? extends AbstractCLI>) Class
                        .forName(bean.getBeanClassName());

                Object cliInstance = aClazz.newInstance();

                Method method = aClazz.getMethod("getCommandName");
                String commandName = (String) method.invoke(cliInstance, new Object[] {});
                if (commandName == null || StringUtils.isBlank(commandName)) {
                    // keep null to avoid printing some commands...
                    continue;
                }

                Method method2 = aClazz.getMethod("getShortDesc");
                String desc = (String) method2.invoke(cliInstance, new Object[] {});

                Method method3 = aClazz.getMethod("getCommandGroup");
                CommandGroup g = (CommandGroup) method3.invoke(cliInstance, new Object[] {});

                if (!commands.containsKey(g)) {
                    commands.put(g, new TreeMap<String, String>());
                }

                commands.get(g).put(commandName, desc + " (" + bean.getBeanClassName() + ")");

                commandClasses.put(commandName, aClazz);
            } catch (Exception e) {
                // OK, this can happen if we hit a non useful class.
            }
        }
    } catch (Exception e1) {
        System.err.println("ERROR! Report to developers: " + e1.getMessage());
        System.exit(1);
    }

    if (args.length == 0 || args[0].equalsIgnoreCase("--help") || args[0].equalsIgnoreCase("-help")
            || args[0].equalsIgnoreCase("help")) {
        GemmaCLI.printHelp(commands);
    } else {
        LinkedList<String> f = new LinkedList<>(Arrays.asList(args));
        String commandRequested = f.remove(0);
        Object[] argsToPass = f.toArray(new String[] {});

        if (!commandClasses.containsKey(commandRequested)) {
            System.err.println("Unrecognized command: " + commandRequested);
            GemmaCLI.printHelp(commands);
            System.err.println("Unrecognized command: " + commandRequested);
            System.exit(1);
        } else {
            try {
                Class<?> c = commandClasses.get(commandRequested);
                Method method = c.getMethod("main", String[].class);
                System.err.println("========= Gemma CLI invocation of " + commandRequested + " ============");
                System.err.println("Options: " + GemmaCLI.getOptStringForLogging(argsToPass));
                //noinspection JavaReflectionInvocation // It works
                method.invoke(null, (Object) argsToPass);
            } catch (Exception e) {
                System.err.println("Gemma CLI error: " + e.getClass().getName() + " - " + e.getMessage());
                System.err.println(ExceptionUtils.getStackTrace(e));
                throw new RuntimeException(e);
            } finally {
                System.err.println("========= Gemma CLI run of " + commandRequested + " complete ============");
                System.exit(0);
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) {

    // create a LinkedList
    LinkedList<String> list = new LinkedList<String>();

    // add some elements
    list.add("Hello");
    list.add("tutorial from java2s.com");
    list.add("10");

    // print the list
    System.out.println("LinkedList:" + list);

    // remove "10"
    System.out.println("10 is in the list:" + list.remove("10"));

    // print the list
    System.out.println("LinkedList:" + list);
}

From source file:MainClass.java

public static void main(String args[]) {

    LinkedList<String> ll = new LinkedList<String>();

    ll.add("B");/*from   ww  w  . jav  a 2 s  .  co m*/
    ll.add("C");
    ll.add("D");
    ll.add("E");
    ll.add("F");
    ll.addLast("Z");
    ll.addFirst("A");

    ll.add(1, "A2");

    System.out.println("Original contents of ll: " + ll);

    ll.remove("F");
    ll.remove(2);

    System.out.println("Contents of ll after deletion: " + ll);

    ll.removeFirst();
    ll.removeLast();

    System.out.println("ll after deleting first and last: " + ll);

    String val = ll.get(2);
    ll.set(2, val + " Changed");

    System.out.println("ll after change: " + ll);
}

From source file:Main.java

public static void main(String[] args) {

    // create a LinkedList
    LinkedList<String> list = new LinkedList<String>();

    // add some elements
    list.add("Hello");
    list.add("Chocolate");
    list.add("10");

    // print the list
    System.out.println("LinkedList:" + list);

    // remove the element at index 2
    System.out.println("Element to be removed:" + list.remove(2));

    // print the list
    System.out.println("LinkedList:" + list);
}

From source file:LinkedListExample.java

public static void main(String[] args) {
    // Create a new LinkedList
    LinkedList<Integer> list = new LinkedList<Integer>();

    // Add Items to the array list
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add(new Integer(3));
    list.add(new Integer(4));
    list.add(new Integer(5));
    list.add(new Integer(6));
    list.add(new Integer(7));
    list.add(new Integer(8));
    list.add(new Integer(9));
    list.add(new Integer(10));

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }/*from  w w  w .ja v  a2s . com*/

    // Remove the element at index 5 (value=6)
    list.remove(5);

    // Set the value at index 5, this overwrites the value 7
    list.set(5, new Integer(66));

    // Use the linked list as a queue:
    // add an object to the end of the list (queue)
    // remove an item from the head of the list (queue)
    list.addLast(new Integer(11));
    Integer head = (Integer) list.removeFirst();
    System.out.println("Head: " + head);

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {/*ww w  .j  av a2  s. co  m*/
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static <V> void splice(LinkedList<V> list, Iterator<V> iterator, LinkedList<V> list2, V v) {
    list2.remove(v);
    assert (iterator.equals(list.iterator()));

    list.addFirst(v);/* ww w. ja v a2  s  .  c  o  m*/
}

From source file:org.semanticscience.narf.graphs.lib.cycles.CycleHelper.java

/**
 * Rotate a list counterclockwise by one step. relative positioning of
 * elements remains the same for example: [a,b,c] -> [b,a,c]
 * /*from ww w.j  a v  a 2s.  c om*/
 * @param aSortedList
 *            a sorted list of edges that belong to a cycle
 * @return a rotated edge list that preserves relative positioning of
 *         elements
 */
private static LinkedList<InteractionEdge> rotateCounterClockwise(LinkedList<InteractionEdge> aSortedList) {
    LinkedList<InteractionEdge> rm = new LinkedList<InteractionEdge>();
    rm = aSortedList;
    // remove the first element
    InteractionEdge f = rm.remove(0);
    // now add it at the end
    rm.add(f);
    return rm;
}

From source file:voldemort.utils.RebalanceUtils.java

/**
 * Given a interim cluster with a previously vacated zone, constructs a new
 * cluster object with the drop zone completely removed
 * /*from   www  . ja v a 2 s  . c o  m*/
 * @param intermediateCluster
 * @param dropZoneId
 * @return adjusted cluster with the zone dropped
 */
public static Cluster dropZone(Cluster intermediateCluster, int dropZoneId) {
    // Filter out nodes that don't belong to the zone being dropped
    Set<Node> survivingNodes = new HashSet<Node>();
    for (int nodeId : intermediateCluster.getNodeIds()) {
        if (intermediateCluster.getNodeById(nodeId).getZoneId() != dropZoneId) {
            survivingNodes.add(intermediateCluster.getNodeById(nodeId));
        }
    }

    // Filter out dropZoneId from all zones
    Set<Zone> zones = new HashSet<Zone>();
    for (int zoneId : intermediateCluster.getZoneIds()) {
        if (zoneId == dropZoneId) {
            continue;
        }
        LinkedList<Integer> proximityList = intermediateCluster.getZoneById(zoneId).getProximityList();
        proximityList.remove(new Integer(dropZoneId));
        zones.add(new Zone(zoneId, proximityList));
    }

    return new Cluster(intermediateCluster.getName(), Utils.asSortedList(survivingNodes),
            Utils.asSortedList(zones));
}