官术网_书友最值得收藏!

Iterating through Collections

Earlier in this chapter, when working with Exercise 01, Creating the AnalyzeInput Application we stopped when we were about to make searches through the data. We made it to the point where we had to iterate through the data and look for characteristics such as word frequency.

Iterators are used in Java to browse through collections. Let's look at a simple example that involves extracting the elements from a simple list one by one and printing them out.

import java.util.*;

public class Example16 {

    public static void main(String[] args) {

        List array = new ArrayList();

        array.add(5);

        array.add(2);

        array.add(37);

        Iterator iterator = array.iterator();

        while (iterator.hasNext()) {

            // point to next element

            int i = (Integer) iterator.next();

            // print elements

            System.out.print(i + " ");

        }

    }

}

The output of this program is:

5 2 37

Process finished with exit code 0

Iterators such as this one are the most generic ones in the collections framework and can be used with lists, sets, queues, and even maps. There are other less-broad implementations of the iterators that allow for different ways to browse through data, for example, in lists. As you saw in the latest code listing, the iterator.hasNext() method checks whether there is a node after the one we are at in the list. When starting the iterator, the object points to the first element in the list. Then, hasNext() responds with a Boolean stating whether there are more nodes hanging from it. The iterator.next() method will move the iterator to the following node in the collection. This kind of iterator does not have the possibility of going back in the collection; it can only move forward. There is one final method in the iterator, called remove(), which will eliminate the current element that the iterator is pointing to from the collection.

If we used listIterator() instead, we would have had a lot more options for navigating collections, such as adding new elements and changing elements. The following code listing demonstrates how to go through a list, add elements, and modify them. listIterator works only with lists:

import java.util.*;

public class Example17 {

    public static void main(String[] args) {

        List <Double> array = new ArrayList();

        array.add(5.0);

        array.add(2.2);

        array.add(37.5);

        array.add(3.1);

        array.add(1.3);

        System.out.println("Original list: " + array);

        ListIterator listIterator = array.listIterator();

        while (listIterator.hasNext()) {

            // point to next element

            double d = (Double) listIterator.next();

            // round up the decimal number

            listIterator.set(Math.round(d));

        }

        System.out.println("Modified list: " + array);

    }

}

In this example, we create a list of Double, iterate through the list, and round up each of the numbers. The outcome of this program is:

Original list: [5.0, 2.2, 37.5, 3.1, 1.3]

Modified list: [5, 2, 38, 3, 1]

Process finished with exit code 0

By calling listIterator.set(), we modify each of the items in the list and the second System.out.println() command shows where the numbers have been rounded up or down.

The final iterator example we are going to see in this section is a trick to iterate through a map. This could come in handy in scenarios where you want to perform some operations on data within a map. By using the entrySet() method – which returns a list – it is possible to have an iterator over a map. See the following example to understand how this works:

import java.util.*;

public class AnalyzeInput {

     public static void main(String[] args) {

        Map map = new HashMap ();

        map.put("name", "Kristian");

        map.put("family name", "Larssen");

        map.put("address", "Jumping Rd");

        map.put("mobile", "555-12345");

        map.put("pet", "cat");

        Iterator <Map.Entry> iterator = map.entrySet().iterator();

        while (iterator.hasNext()) {

            Map.Entry entry = iterator.next();

            System.out.print("Key = " + entry.getKey());

            System.out.println( ", Value = " + entry.getValue());

        }

    }

}

This program will iterate through a map and print the contents as they were stored in HashMap. Remember that these types of objects are not sorted in any specific way. You can expect an output like the following:

Key = address, Value = Jumping Rd

Key = family name, Value = Larssen

Key = name, Value = Kristian

Key = mobile, Value = 555-12345

Key = pet, Value = cat

Process finished with exit code 0

Given that we now have ways to iterate through collections, we can move on to an exercise that picks up where we left off: iterating through a list for data analysis.

Exercise 2: Bringing Analytics into the AnalyzeInput Application

We are going to start from where we left off at the end of Exercise 1, Creating the AnalyzeInput Application. We managed to capture the text typed in the terminal and store it as a list of strings. This time, we are going to use a method from the collections framework called frequency, which will respond with the number of times a certain object can be found inside a list. As words could be repeated in a sentence, we first need to figure out a way to extract the unique elements in a list:

  1. Sets are objects in the collections framework that keep only one copy of each element. We saw an example of this earlier in the chapter. We will create a HashSet instance and copy all the elements from the list into it. This will automatically eliminate duplicates:

    Set <String> textSet = new HashSet <String> ();

    textSet.addAll(text);

  2. The next step, now that we have the set, is to create an iterator that will check how many copies of each element from the set can be found in the list:

    Iterator iterator = textSet.iterator();

  3. Using the same technique that we saw in previous examples for how to iterate through a set, we will find the next node in the set and check in the list for the frequency of the string stored in the node:

    while (iterator.hasNext()) {

        //point to next element

        String s = (String) iterator.next();

        // get the amount of times this word shows up in the text

        int freq = Collections.frequency(text, s);

        // print out the result

        System.out.println(s + " appears " + freq + " times");

    }

    Note

    The final code can be referred at: https://packt.live/2BrplvS.

  4. The outcome will depend on the kind of text you type. For the sake of testing, try the following (we will stick to this data entry for the rest of the chapter – you can copy and paste it to the terminal each time you call the application):

    this is a test

    is a test

    test is this

    *

  5. The full outcome of this input will be:

    You typed: [this, is, a, test, is, a, test, test, is, this, *]

    Word count: 11

    a appears 2 times

    test appears 3 times

    this appears 2 times

    is appears 3 times

    * appears 1 times

    While the result is correct, it is not easy to read through. Ideally, results should be sorted. For example, by descending values of frequency, so that it is easy to see at a glance the most and least frequent words. This is the time to make yet another stop in the exercise as we need to introduce the idea of sorting before we move on with it.

主站蜘蛛池模板: 怀宁县| 平谷区| 曲麻莱县| 延庆县| 营山县| 宁津县| 双柏县| 通化市| 土默特右旗| 黄龙县| 科技| 浠水县| 屏山县| 敦煌市| 沧源| 阜平县| 武平县| 九江市| 芜湖市| 永清县| 廉江市| 获嘉县| 青冈县| 河北区| 策勒县| 临湘市| 宿迁市| 行唐县| 津市市| 宝清县| 天津市| 永寿县| 明光市| 张掖市| 宜宾县| 凯里市| 南昌县| 鹤山市| 西乌珠穆沁旗| 黄浦区| 潞西市|