View difference between Paste ID: WFMiV5tC and yQcav68z
SHOW: | | - or go back to the newest paste.
1
// Say we have a List of names and we would like to find all those names where "am" occurs:
2
{
3
  // LINQ
4
  // string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
5
  // List<string> filteredNames = names.Where(c => c.Contains("am"))
6
  //                                   .ToList();
7
 
8
  // Java Streams
9
  // String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
10
  // List<String> filteredNames = stream(names)
11
  //                  .filter(c -> c.contains("am"))
12
  //                  .collect(toList());
13
 
14
  val names = Array("Sam", "Pamela", "Dave", "Pascal", "Erik")
15
  val filteredNames = names filter(_.contains("am")) toList
16
}
17
 
18
// Find all the names in the array "names" where the length of the name is less than or equal to
19
// the index of the element + 1.
20
{
21
  // LINQ
22
  // string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
23
  // var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
24
 
25
  // Java Streams
26
  // String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
27
  // OfInt indices = IntStream.range(1, names.length).iterator();
28
  // List<String> nameList = stream(names).map(c -> Pair.of(indices.next(), c))
29-
                                      .filter(c -> c.getValue().length() <= c.getKey())
29+
  //                                    .filter(c -> c.getValue().length() <= c.getKey())
30-
                                      .map(Pair::getValue)
30+
  //                                    .map(Pair::getValue)
31-
                                      .collect(toList());
31+
  //                                    .collect(toList());
32
 
33
  val names = Array("Sam", "Pamela", "Dave", "Pascal", "Erik")
34
  val nameList = names.zipWithIndex collect {
35
    case (c, index) if (c.length <= index+1) => c
36
  } toList
37
}
38
 
39
// Say we have a list of names and we would like to print β€œHello” in front of all the names:
40
{
41
  // LINQ
42
  // List<string> nameList1 = new List(){ "Anders", "David", "James",
43
  //                                      "Jeff", "Joe", "Erik" };
44
  // nameList1.Select(c => "Hello! " + c).ToList()
45
  //          .ForEach(c => Console.WriteLine(c));
46
 
47
  // Java Streams
48
  // List<String> nameList1 = asList("Anders", "David", "James",
49
  //                                 "Jeff", "Joe", "Erik");
50
  // nameList1.stream()
51
  //      .map(c -> "Hello! " + c)
52
  //      .forEach(System.out::println);
53
 
54
  // Scala
55
  val nameList1 = List("Anders", "David", "James", "Jeff", "Joe", "Erik")
56
  nameList1 foreach { n => println(s"Hello! $n") }
57
}
58
 
59
// Suppose, we have a dictionary such that each key has a list of values attached to them. Now,
60
// we want to project all the elements in a single collection:
61
{
62
  // LINQ
63
  // Dictionary<string, List<string>> map = new Dictionary<string,List<string>>();
64
  // map.Add("UK", new List<string>() {"Bermingham", "Bradford", "Liverpool"});
65
  // map.Add("USA", new List<string>() {"NYC", "New Jersey", "Boston", "Buffalo"});
66
  // var cities = map.SelectMany(c => c.Value).ToList();
67
 
68
  // Java Streams
69
  // Map<String, List<String>> map = new LinkedHashMap<>();
70
  // map.put("UK", asList("Bermingham","Bradford","Liverpool"));
71
  // map.put("USA", asList("NYC","New Jersey","Boston","Buffalo"));
72
  // List<String> cities = map.entrySet().stream()
73
  //                                   .map(Map.Entry::getValue)
74
  //                                   .flatMap(List::stream)
75
  //                                   .collect(toList());
76
 
77
  val map = Map("UK" -> List("Bermingham", "Bradford", "Liverpool"),
78
                "USA" -> List("NYC", "New Jersey", "Boston", "Buffalo"))
79
  val cities = map.values.flatten
80
}
81
 
82
// In this case we are interested in evaluating only the first n elements of a collection. For
83
// instance, using a finite list of numbers, obtain the first 4 of them.
84
{
85
  // LINQ
86
  // int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
87
  // var first4 = numbers.Take(4).ToList();
88
 
89
  // Java Streams
90
  // int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13 };
91
  // List<Integer> firstFour = stream(numbers).limit(4)
92
  //                            .boxed()
93
  //                            .collect(toList());
94
95
  val numbers = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
96
  val first4 = numbers take(4) toList
97
}
98
 
99
// In this case we are interested in taking items out of a collection as long as they satisfy a
100
// predicate. Once we find an item that does not satisfy the predicate we stop there.
101
{
102
  // LINQ
103
  // string[] moreNames = { "Sam", "Samuel", "Dave", "Pascal", "Erik",  "Sid" };
104
  // var sNames = moreNames.TakeWhile(c => c.StartsWith("S"));
105
 
106
  // Java Streams
107
  // String[] names  = { "Sam","Samuel","Dave","Pascal","Erik","Sid" };
108
  // List<String> found = stream(names).collect(partitioningBy( c -> c.startsWith("S")))
109
  //                      .get(true);
110
 
111
  val moreNames = Array("Sam", "Samuel", "Dave", "Pascal", "Erik",  "Sid")
112
  val sNames = moreNames takeWhile(_ startsWith "S") toList
113
}
114
 
115
// In this case we are interested in skipping items in a collection up to certain arbitrary
116
// number, then we keep the rest of the items.
117
{
118
  // LINQ
119
  // string[] vipNames = { "Sam", "Samuel", "Samu", "Remo", "Arnold","Terry" };
120
  // var skippedList = vipNames.Skip(3).ToList();//Leaving the first 3.
121
 
122-
  // Java
122+
123
  // String[] vipNames = { "Sam", "Samuel", "Samu", "Remo", "Arnold","Terry" };
124
  // List<String> skippedList = stream(vipNames).skip(3).collect(toList());
125
 
126
  val vipNames = Array("Sam", "Samuel", "Samu", "Remo", "Arnold", "Terry")
127
  val skippedList = vipNames drop(3) toList
128
}
129
 
130
// In this case we are interested in skipping items out of a collection as long as they satisfy a
131
// predicate. Once we find an item that does not satisfy the predicate we take the rest of the
132
// items from there.
133
{
134
  // LINQ
135
  // int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 20 };
136
  // var skippedList = numbers.SkipWhile(c => c < 10);
137
 
138-
  // Java
138+
139
  // With current streams API I found no way to implement this idiom.
140
 
141
  val numbers = Seq(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 20)
142
  val skippedList = numbers dropWhile(_ < 10)
143
}
144
 
145
// Order the elements of a collection alphabetically:
146
{
147
  // LINQ
148
  // string[] friends = { "Sam", "Pamela", "Dave", "Anders", "Erik" };
149
  // string[] sortedFriends = friends.OrderBy(c => c).ToArray();
150
 
151
  // Java Streams
152
  // String[] friends = { "Sam", "Pamela", "Dave", "Anders", "Erik" };
153
  // String[] sortedFriends = stream(friends).sorted().toArray(String[]::new);
154
 
155
  val friends = Array("Sam", "Pamela", "Dave", "Anders", "Erik")
156
  val sortedFriends = friends.sorted
157
}
158
 
159
// Order the elements of a collection strings according to the length of the string:
160
{
161
  // LINQ
162
  // string[] friends = { "Sam", "Pamela", "Dave", "Anders", "Erik" };
163
  // friends = friends.OrderBy(c => c.Length).ToArray();
164
 
165
  // Java Streams
166
  // String[] friends = { "Sam", "Pamela", "Dave", "Anders", "Erik" };
167
  // friends = stream(friends).sorted(comparing(String::length)).toArray(String[]::new);
168
 
169
  var friends = Array("Sam", "Pamela", "Dave", "Anders", "Erik")
170
  friends = friends.sortBy(_.length)
171
}
172
 
173
// Order the elements of a collection of strings according to several sorting criteria:
174
{
175
  // LINQ
176
  // string[] fruits = {"grape", "passionfruit", "banana",
177
  //                    "apple", "orange", "raspberry",
178
  //                    "mango", "blueberry" };
179
  // var sortedFruits = fruits.OrderBy(fruit =>fruit.Length)
180
  //                          .ThenBy(fruit => fruit);
181
  // Java Streams
182
  // String[] fruits = {"grape", "passionfruit", "banana","apple", "orange", "raspberry" };
183
  // String[] sortedFruits = stream(fruits).sorted(comparing(String::length)
184
  //                                      .thenComparing(naturalOrder()))
185
  //                               	  .toArray(String[]::new);
186
 
187
  val fruits = Array("grape", "passionfruit", "banana", "apple",
188
                     "orange", "raspberry", "mango", "blueberry")
189
  val sortedFruits = fruits sortBy(f => (f.length, f))
190
}
191
 
192
// Group the elements of a collection of strings by their length.
193
{
194
  // LINQ
195
  // string[] names = {"Sam", "Samuel", "Samu", "Ravi", "Ratna",  "Barsha"};
196
  // var groups = names.GroupBy(c => c.Length);
197
 
198
  // Java Streams
199
  // String[] names = {"Sam", "Samuel", "Samu", "Ravi", "Ratna",  "Barsha"};
200
  // Map<Integer,List<String>> groups = stream(names).collect(groupingBy(String::length));
201
 
202
  val names = Array("Sam", "Samuel", "Samu", "Ravi", "Ratna",  "Barsha")
203
  val groups = names groupBy(_.length)
204
}
205
 
206
// Obtain all the distinct elements from a collection.
207
{
208
  // LINQ
209
  // string[] songIds = {"Song#1", "Song#2", "Song#2", "Song#2", "Song#3", "Song#1"};
210
  // //This will work as strings implement IComparable
211
  // var uniqueSongIds = songIds.Distinct();
212
 
213
  // Java Streams
214
  // String[] songIds = {"Song#1", "Song#2", "Song#2", "Song#2", "Song#3", "Song#1"};
215
  // List<String> uniqueSongIds = stream(songIds).distinct().collect(toList());
216
 
217
  val songIds = Array("Song#1", "Song#2", "Song#2", "Song#2", "Song#3", "Song#1")
218
  val uniqueSongIds = songIds.distinct
219
}
220
 
221
// Join together two sets of items.
222
{
223
  // LINQ
224
  // List<string> friends1 = new List<string>() {"Anders", "David","James",
225
  //                                             "Jeff", "Joe", "Erik"};
226
  // List<string> friends2 = new List<string>() { "Erik", "David", "Derik" };
227
  // var allMyFriends = friends1.Union(friends2);
228
 
229
  // Java Streams
230
  // List<String> friends1 = asList("Anders","David","James","Jeff","Joe","Erik");
231
  // List<String> friends2 = asList("Erik","David","Derik");
232
  // Stream<String> allMyFriends = Stream.concat(friends1.stream(), friends2.stream())
233
  //                                .collect(toSet());
234
 
235
  val friends1 = List("Anders", "David","James", "Jeff", "Joe", "Erik")
236
  val friends2 = List("Erik", "David", "Derik")
237
  val allMyFriends = Set() ++ friends1 ++ friends2
238
}
239
 
240
// Obtain the first element of a collection.
241
{
242
  // LINQ
243
  // string[] otherFriends = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
244
  // string firstName = otherFriends.First();
245
  // string firstNameConditional = otherFriends.First(c => c.Length == 5);
246
 
247
  // Java Streams
248
  // String[] otherFriends = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
249
  // Optional<String> firstName = stream(otherFriends).findFirst();
250
  // Optional<String> firstNameConditional = stream(otherFriends).filter(c -> c.length() == 5)
251
                                                       .findFirst();
252
253
  val otherFriends = Array("Sam", "Danny", "Jeff", "Erik", "Anders","Derik")
254
  val firstName = otherFriends.head
255
  val firstNameConditional = otherFriends.find(_.length == 5)
256
}
257
 
258
// Generate a range of numbers that are multiples of 11.
259
{
260
  // LINQ
261
  // var multiplesOfEleven = Enumerable.Range(1, 100).Where(c => c % 11 == 0);
262
 
263
  // Java Streams
264
  // List<Integer> multiplesOfEleven = IntStream.rangeClosed(1,100)
265
  //                                          .filter(n -> n % 11 == 0)
266
  //                                          .boxed()
267
  //                                          .collect(toList());
268
 
269
  val multiplesOfEleven = (1 to 100) filter(_ % 11 == 0)
270
}
271
 
272
// Do all elements in a collection satisfy a predicate?
273
{
274
  // LINQ
275
  // string[] persons = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
276
  // bool x = persons.All(c => c.Length == 5);
277
 
278
  // Java Streams
279
  // String[] persons = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
280
  // boolean x = stream(persons).allMatch(c -> c.length() == 5);
281
 
282
  val persons = Array("Sam", "Danny", "Jeff", "Erik", "Anders","Derik")
283
  val x = persons.forall(_.length == 5)
284
}
285
 
286
// Do any elements in a collection satisfy a predicate?
287
{
288
  // LINQ
289
  // string[] persons = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
290
  // bool x = persons.Any(c => c.Length == 5);
291
 
292
  // Java Streams
293
  // String[] persons = {"Sam", "Danny", "Jeff", "Erik", "Anders","Derik"};
294
  // boolean x = stream(persons).anyMatch(c -> c.length() == 5);
295
 
296
  val persons = Array("Sam", "Danny", "Jeff", "Erik", "Anders","Derik")
297
  val x = persons.exists(_.length == 5)
298
}
299
 
300
// Combine two collections into a single collection.
301
{
302
  // LINQ
303
  // string[] salutations = {"Mr.", "Mrs.", "Ms", "Master"};
304
  // string[] firstNames = {"Samuel", "Jenny", "Joyace", "Sam"};
305
  // string lastName = "McEnzie";
306
  // salutations.Zip(firstNames, (sal, first) => sal + " " + first)
307
  //            .ToList()
308
  //            .ForEach(c => Console.WriteLine(c + " " + lastName));
309
 
310
  // Java Streams
311
  // String[] salutations = {"Mr.", "Mrs.", "Ms", "Master"};
312
  // String[] firstNames = {"Samuel", "Jenny", "Joyace", "Sam"};
313
  // String lastName = "McEnzie";
314
  // Iterator<String> sal = stream(salutations).iterator();
315
  // stream(firstNames).map(c -> sal.next() + " " + c + " " + lastName)
316
  //                .forEach(System.out::println);
317
 
318
  val salutations = Array("Mr.", "Mrs.", "Ms", "Master")
319
  val firstNames = Array("Samuel", "Jenny", "Joyace", "Sam")
320
  val lastName = "McEnzie"
321
  salutations zip(firstNames) map { case (sal, first) => s"$sal $first" } foreach {
322
    c => println(s"$c $lastName") }
323
  // salutations zip(firstNames) foreach { case (sal, first) => println(s"$sal $first $lastName") }
324
}