|
| 1 | +package org.codewithease.javatopics.ArraysANDCollections; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +public class Demo { |
| 10 | + |
| 11 | + /* |
| 12 | +
|
| 13 | +Implement a function to reverse the order of elements in an ArrayList using the Collections class. |
| 14 | +Write a program to find the frequency of elements in an ArrayList using the Collections class. |
| 15 | +Implement a function to check if two arrays are equal using the Arrays class. |
| 16 | +Create a method to shuffle the elements in an ArrayList using the Collections class. |
| 17 | +Write a program to convert an ArrayList to an array using the toArray() method. |
| 18 | +Implement a function to find the index of a specific element in an ArrayList using the Collections class. |
| 19 | + */ |
| 20 | + |
| 21 | + |
| 22 | + public static void main(String[] args) { |
| 23 | + |
| 24 | + //Write a program to find the maximum element in an array using the Arrays class. |
| 25 | + int[] array = {5, 8, 3, 2, 9, 1}; |
| 26 | + int max = Arrays.stream(array).max().orElse(0); |
| 27 | + System.out.println(max); |
| 28 | + |
| 29 | + |
| 30 | + //Implement a function to remove duplicates from an ArrayList using the Collections class. |
| 31 | + |
| 32 | + List<Integer> list = Arrays.asList(3, 5, 3, 2, 1, 5); |
| 33 | + list.stream().distinct().collect(Collectors.toList()).forEach(System.out::println); |
| 34 | + |
| 35 | + |
| 36 | + System.out.println("sort descending"); |
| 37 | + //Create a method to sort an ArrayList in descending order using the Collections class. |
| 38 | + |
| 39 | +// list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList()).forEach(System.out::println); |
| 40 | + Collections.sort(list, Collections.reverseOrder()); |
| 41 | + System.out.println("Sorted list in descending order: " + list); |
| 42 | + |
| 43 | + //Write a program to find the common elements between two arrays using the Arrays class. |
| 44 | + |
| 45 | + Integer[] array1 = {1, 2, 3, 4, 5}; |
| 46 | + Integer[] array2 = {4, 5, 6, 7, 8}; |
| 47 | + ArrayList<Integer> commonElements = new ArrayList<>(Arrays.asList(array1)); |
| 48 | + commonElements.retainAll(Arrays.asList(array2)); |
| 49 | + System.out.println("Common elements: " + commonElements); |
| 50 | + |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | + |
0 commit comments