Example usage for java.util Iterator remove

List of usage examples for java.util Iterator remove

Introduction

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

Prototype

default void remove() 

Source Link

Document

Removes from the underlying collection the last element returned by this iterator (optional operation).

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();/*from   ww w .  jav a  2 s. co m*/
        Iterator it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();

            if (selKey.isAcceptable()) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
                SocketChannel sc = ssChannel.accept();
                ByteBuffer bb = ByteBuffer.allocate(100);
                sc.read(bb);

            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) {
    ArrayList aList = new ArrayList();
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("java2 s .com");
    System.out.println("ArrayList: ");
    System.out.println(aList);//from   w  ww.  ja  v a2 s .c  om
    Iterator itr = aList.iterator();
    String strElement = "";
    while (itr.hasNext()) {
        strElement = (String) itr.next();
        if (strElement.equals("2")) {
            itr.remove();
            break;
        }
    }
    System.out.println("ArrayList after removal : ");
    System.out.println(aList);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Selector selector = Selector.open();

    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
    ssChannel2.configureBlocking(false);
    ssChannel2.socket().bind(new InetSocketAddress(81));

    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
    ssChannel2.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();/*from  w w w  .  java 2 s  .c  om*/
        Iterator it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();

            if (selKey.isAcceptable()) {
                ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
                SocketChannel sc = ssChannel.accept();
                ByteBuffer buf = ByteBuffer.allocate(100);
                int numBytesRead = sc.read(buf);

                if (numBytesRead == -1) {
                    sc.close();
                } else {
                    // Read the bytes from the buffer
                }
                int numBytesWritten = sc.write(buf);
            }
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);/*from  w  ww  .  j a  va 2  s.  c  o m*/

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}

From source file:NewFingerServer.java

public static void main(String[] arguments) throws Exception {
    ServerSocketChannel sockChannel = ServerSocketChannel.open();
    sockChannel.configureBlocking(false);

    InetSocketAddress server = new InetSocketAddress("localhost", 79);
    ServerSocket socket = sockChannel.socket();
    socket.bind(server);/*from ww  w  . j a v a2s. c  om*/

    Selector selector = Selector.open();
    sockChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();
            if (selKey.isAcceptable()) {
                ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
                ServerSocket selSocket = selChannel.socket();
                Socket connection = selSocket.accept();

                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader is = new BufferedReader(isr);
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
                pw.println("NIO Finger Server");
                pw.flush();
                String outLine = null;
                String inLine = is.readLine();
                if (inLine.length() > 0) {
                    outLine = inLine;
                }
                readPlan(outLine, pw);
                pw.flush();
                pw.close();
                is.close();

                connection.close();
            }
        }
    }
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }/*from   www . j  ava  2s . c o  m*/
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) {
    // Create a list of strings
    List<String> names = new ArrayList<>();
    names.add("A");
    names.add("B");
    names.add("C");

    Iterator<String> nameIterator = names.iterator();
    // Iterate over all elements in the list
    while (nameIterator.hasNext()) {
        // Get the next element from the list
        String name = nameIterator.next();
        System.out.println(name);
        nameIterator.remove();
    }/*from ww  w  . j  a v a  2s .  co  m*/
    System.out.println(names);
}

From source file:Main.java

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

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

    for (String str : aList) {
        System.out.println(str);//from www  .j a  v a  2s . co m
    }
    Iterator itr = aList.iterator();

    // remove 2 from ArrayList using Iterator's remove method.

    String strElement = "";

    while (itr.hasNext()) {
        strElement = (String) itr.next();
        if (strElement.equals("2")) {
            itr.remove();
            break;
        }
    }
    for (String str : aList) {
        System.out.println(str);
    }
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*  ww  w  .j  av  a2s  .co m*/
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
    String inputDir = args[0];//from   w  ww  . java  2 s.  c  o  m
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    // for generating ConvArgStrict use this
    String prefix = "no-eq_DescendingScoreArgumentPairListSorter";

    // for oversampling using graph transitivity properties use this
    //        String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter";

    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();

        if (!file.getName().startsWith(prefix)) {
            iterator.remove();
        }
    }

    int totalGoldPairsCounter = 0;

    Map<String, Integer> goldDataDistribution = new HashMap<>();

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    int totalPairsWithReasonSameAsGold = 0;

    DescriptiveStatistics ds = new DescriptiveStatistics();

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        int pairsPerTopicCounter = 0;

        String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", "");

        PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8");

        pw.println("#id\tlabel\ta1\ta2");

        for (AnnotatedArgumentPair argumentPair : argumentPairs) {
            String goldLabel = argumentPair.getGoldLabel();

            if (!goldDataDistribution.containsKey(goldLabel)) {
                goldDataDistribution.put(goldLabel, 0);
            }

            goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1);

            pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel,
                    multipleParagraphsToSingleLine(argumentPair.getArg1().getText()),
                    multipleParagraphsToSingleLine(argumentPair.getArg2().getText()));

            pairsPerTopicCounter++;

            int sameInOnePair = 0;

            // get gold reason statistics
            for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) {
                String label = assignment.getValue();

                if (goldLabel.equals(label)) {
                    sameInOnePair++;
                }
            }

            ds.addValue(sameInOnePair);
            totalPairsWithReasonSameAsGold += sameInOnePair;
        }

        totalGoldPairsCounter += pairsPerTopicCounter;
        statsPerTopic.addValue(pairsPerTopicCounter);

        pw.close();
    }

    System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold);
    System.out.println(ds);

    System.out.println("Total gold pairs: " + totalGoldPairsCounter);
    System.out.println(statsPerTopic);

    int totalPairs = 0;
    for (Integer pairs : goldDataDistribution.values()) {
        totalPairs += pairs;
    }
    System.out.println("Total pairs: " + totalPairs);
    System.out.println(goldDataDistribution);

}