forked from nlharri/JavaCollectionsFrameworkCheatSheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
java-array-list examples
420 lines (335 loc) · 14.1 KB
/
java-array-list examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import java.util.ArrayList;
import java.util.List;
public class AccessElementsFromArrayListExample {
public static void main(String[] args) {
List<String> topCompanies = new ArrayList<>();
// Check if an ArrayList is empty
System.out.println("Is the topCompanies list empty? : " + topCompanies.isEmpty());
topCompanies.add("Google");
topCompanies.add("Apple");
topCompanies.add("Microsoft");
topCompanies.add("Amazon");
topCompanies.add("Facebook");
// Find the size of an ArrayList
System.out.println("Here are the top " + topCompanies.size() + " companies in the world");
System.out.println(topCompanies);
// Retrieve the element at a given index
String bestCompany = topCompanies.get(0);
String secondBestCompany = topCompanies.get(1);
String lastCompany = topCompanies.get(topCompanies.size() - 1);
System.out.println("Best Company: " + bestCompany);
System.out.println("Second Best Company: " + secondBestCompany);
System.out.println("Last Company in the list: " + lastCompany);
// Modify the element at a given index
topCompanies.set(4, "Walmart");
System.out.println("Modified top companies list: " + topCompanies);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListCollectionsSortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(13);
numbers.add(7);
numbers.add(18);
numbers.add(5);
numbers.add(2);
System.out.println("Before : " + numbers);
// Sorting an ArrayList using Collections.sort() method
Collections.sort(numbers);
System.out.println("After : " + numbers);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListIteratorRemoveExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(13);
numbers.add(18);
numbers.add(25);
numbers.add(40);
Iterator<Integer> numbersIterator = numbers.iterator();
while (numbersIterator.hasNext()) {
Integer num = numbersIterator.next();
if(num % 2 != 0) {
numbersIterator.remove();
}
}
System.out.println(numbers);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class ArrayListObjectSortExample {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Sachin", 47));
people.add(new Person("Chris", 34));
people.add(new Person("Rajeev", 25));
people.add(new Person("David", 31));
System.out.println("Person List : " + people);
// Sort People by their Age
people.sort((person1, person2) -> {
return person1.getAge() - person2.getAge();
});
// A more concise way of writing the above sorting function
people.sort(Comparator.comparingInt(Person::getAge));
System.out.println("Sorted Person List by Age : " + people);
// You can also sort using Collections.sort() method by passing the custom Comparator
Collections.sort(people, Comparator.comparing(Person::getName));
System.out.println("Sorted Person List by Name : " + people);
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Lisa");
names.add("Jennifer");
names.add("Mark");
names.add("David");
System.out.println("Names : " + names);
// Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
names.sort(new Comparator<String>() {
@Override
public int compare(String name1, String name2) {
return name1.compareTo(name2);
}
});
// The above `sort()` method call can also be written simply using lambda expression
names.sort((name1, name2) -> name1.compareTo(name2));
// Following is an even more concise solution
names.sort(Comparator.naturalOrder());
System.out.println("Sorted Names : " + names);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.List;
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ArrayListUserDefinedObjectExample {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User("Rajeev", 25));
users.add(new User("John", 34));
users.add(new User("Steve", 29));
users.forEach(user -> {
System.out.println("Name : " + user.getName() + ", Age : " + user.getAge());
});
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Lisa");
names.add("Jennifer");
names.add("Mark");
names.add("David");
System.out.println("Names : " + names);
// Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
names.sort(new Comparator<String>() {
@Override
public int compare(String name1, String name2) {
return name1.compareTo(name2);
}
});
// The above `sort()` method call can also be written simply using lambda expression
names.sort((name1, name2) -> name1.compareTo(name2));
// Following is an even more concise solution
names.sort(Comparator.naturalOrder());
System.out.println("Sorted Names : " + names);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.List;
public class CreateArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of String using
List<String> animals = new ArrayList<>();
// Adding new elements to the ArrayList
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals);
// Adding an element at a particular index in an ArrayList
animals.add(2, "Elephant");
System.out.println(animals);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.List;
public class CreateArrayListFromCollectionExample {
public static void main(String[] args) {
List<Integer> firstFivePrimeNumbers = new ArrayList<>();
firstFivePrimeNumbers.add(2);
firstFivePrimeNumbers.add(3);
firstFivePrimeNumbers.add(5);
firstFivePrimeNumbers.add(7);
firstFivePrimeNumbers.add(11);
// Creating an ArrayList from another collection
List<Integer> firstTenPrimeNumbers = new ArrayList<>(firstFivePrimeNumbers);
List<Integer> nextFivePrimeNumbers = new ArrayList<>();
nextFivePrimeNumbers.add(13);
nextFivePrimeNumbers.add(17);
nextFivePrimeNumbers.add(19);
nextFivePrimeNumbers.add(23);
nextFivePrimeNumbers.add(29);
// Adding an entire collection to an ArrayList
firstTenPrimeNumbers.addAll(nextFivePrimeNumbers);
System.out.println(firstTenPrimeNumbers);
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IterateOverArrayListExample {
public static void main(String[] args) {
List<String> tvShows = new ArrayList<>();
tvShows.add("Breaking Bad");
tvShows.add("Game Of Thrones");
tvShows.add("Friends");
tvShows.add("Prison break");
System.out.println("=== Iterate using Java 8 forEach and lambda ===");
tvShows.forEach(tvShow -> {
System.out.println(tvShow);
});
System.out.println("\n=== Iterate using an iterator() ===");
Iterator<String> tvShowIterator = tvShows.iterator();
while (tvShowIterator.hasNext()) {
String tvShow = tvShowIterator.next();
System.out.println(tvShow);
}
System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ===");
tvShowIterator = tvShows.iterator();
tvShowIterator.forEachRemaining(tvShow -> {
System.out.println(tvShow);
});
System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ===");
// Here, we start from the end of the list and traverse backwards.
ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size());
while (tvShowListIterator.hasPrevious()) {
String tvShow = tvShowListIterator.previous();
System.out.println(tvShow);
}
System.out.println("\n=== Iterate using simple for-each loop ===");
for(String tvShow: tvShows) {
System.out.println(tvShow);
}
System.out.println("\n=== Iterate using for loop with index ===");
for(int i = 0; i < tvShows.size(); i++) {
System.out.println(tvShows.get(i));
}
}
}
**************************************************************************************************************************************************************************
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class RemoveElementsFromArrayListExample {
public static void main(String[] args) {
List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("Java");
programmingLanguages.add("Kotlin");
programmingLanguages.add("Python");
programmingLanguages.add("Perl");
programmingLanguages.add("Ruby");
System.out.println("Initial List: " + programmingLanguages);
// Remove the element at index `5`
programmingLanguages.remove(5);
System.out.println("After remove(5): " + programmingLanguages);
// Remove the first occurrence of the given element from the ArrayList
// (The remove() method returns false if the element does not exist in the ArrayList)
boolean isRemoved = programmingLanguages.remove("Kotlin");
System.out.println("After remove(\"Kotlin\"): " + programmingLanguages);
// Remove all the elements that exist in a given collection
List<String> scriptingLanguages = new ArrayList<>();
scriptingLanguages.add("Python");
scriptingLanguages.add("Ruby");
scriptingLanguages.add("Perl");
programmingLanguages.removeAll(scriptingLanguages);
System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages);
// Remove if the element matches a given predicate
programmingLanguages.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return s.startsWith("C");
}
});
/*
The above removeIf() call can also be written using lambda expression like this -
programmingLanguages.removeIf(s -> s.startsWith("C"))
*/
System.out.println("After Removing all elements that start with \"C\": " + programmingLanguages);
// Remove all elements from the ArrayList
programmingLanguages.clear();
System.out.println("After clear(): " + programmingLanguages);
}
}