Suppose we’re writing an RSS feed reader and we want to frequently update the feeds, but we don’t care about the order. We can store the feed URLs in a Set. Assume we have the following feeds stored in two Sets:
| val feeds1 = Set("blog.toolshed.com", "pragdave.me", "blog.agiledeveloper.com") |
| val feeds2 = Set("blog.toolshed.com", "martinfowler.com/bliki") |
If we want to update only select feeds from feeds1, say the ones that have the word “blog,” we can get those feeds using the filter method:
| val blogFeeds = feeds1 filter ( _ contains "blog" ) |
| println(s"blog feeds: ${blogFeeds.mkString(", ")}") |
We’ll get this output:
| blog feeds: blog.toolshed.com, blog.agiledeveloper.com |
The mkString method creates a string representation of each element of a Set and concatenates the results with the argument string, a comma in this example.
To merge two Sets of feeds to create a new Set, we can use the ++ method:
| val mergedFeeds = feeds1 ++ feeds2 |
| println(s"# of merged feeds: ${mergedFeeds.size}") |
Set will hold an element at most once, so, as we can see in the output, the common feeds in the two sets will be stored only once in the merged set:
| # of merged feeds: 4 |
To determine what feeds we have in common with a friend’s, we can import our friend’s feeds and perform the intersect operation (&):
| val commonFeeds = feeds1 & feeds2 |
| println(s"common feeds: ${commonFeeds.mkString(", ")}") |
Here’s the effect of the intersect operation on the two previous feeds:
| common feeds: blog.toolshed.com |
To prefix each feed with the string “http://,” use the map method. This applies the given function value to each element, collects the result into a Set, and finally returns that set:
| val urls = feeds1 map ( "http://" + _ ) |
| println(s"One url: ${urls.head}") |
We should see this:
| One url: http://blog.toolshed.com |
Finally, when we’re ready to iterate over the feeds and refresh them one at a time, we can use the built-in iterator foreach like this:
| println("Refresh Feeds:") |
| feeds1 foreach { feed => println(s" Refreshing $feed...") } |
Here’s the result:
| Refresh Feeds: |
| Refreshing blog.toolshed.com... |
| Refreshing pragdave.me... |
| Refreshing blog.agiledeveloper.com... |
So that’s the unordered collection of elements. Next let’s explore the associative map.
3.131.152.166