To append or prepend one or more elements to a
Seq, use these methods:
One thing I never thought about before is that if you need to get multiple, unique, random elements from a list of elements, one solution to the problem is to shuffle the list and then take as many elements as you want/need. For instance, if you want three unique, random elements from a list of integers in Scala, you can do this:
scala> val list = List(1,2,3,4,5,1,2,3,4,5) list: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) scala> val uniq = list.distinct uniq: List[Int] = List(1, 2, 3, 4, 5) scala> val shuffled = scala.util.Random.shuffle(uniq) shuffled: List[Int] = List(1, 4, 5, 2, 3) scala> val firstThree = shuffled.take(3) firstThree: List[Int] = List(1, 4, 5)
As that solution shows, you start with a simple list; get the unique/distinct elements from the list; shuffle those elements to create a new list; then take the first three elements from the shuffled list. That’s probably not a great solution for huge lists, but for many simple lists it’s a way to get multiple random elements from the list.
If you need to iterate over the elements in a
Map in Java 8, this source code shows how to do it:
Map<String, String> map = new HashMap<String, String>(); map.put("first_name", "Alvin"); map.put("last_name", "Alexander"); // java 8 map.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));
I haven’t done any HTML5-specific web programming in a while, so although I know many of the HTML5 tags, I don’t know them all. Here’s a link to the HTML Element Reference page on w3schools.com.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.26, “How to Add Elements to a Set in Scala”
You want to add elements to a mutable set, or create a new set by adding elements to an immutable set.
Mutable and immutable sets are handled differently, as demonstrated in the following examples.
Add elements to a mutable
Set with the
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.9, “How to Delete Array and ArrayBuffer Elements in Scala”
You want to delete elements from an
ArrayBuffer is a mutable sequence, so you can delete elements with the usual
You can remove one or more elements with
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.4, “How to Delete Elements from a List (or `ListBuffer`) in Scala”
You want to delete elements from a
List is immutable, so you can’t delete elements from it, but you can filter out the elements you don’t want while you assign the result to a new variable:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.21, “How to Extract Unique Elements from a Scala Sequence”
You have a collection that contains duplicate elements, and you want to remove the duplicates.
distinct method on the collection: