In this tutorial, we will see “How to remove duplicates from ArrayList using Java 8”. In order to remove duplicates from the list, we are going to use Stream API introduced in Java 8.
Remove duplicates from ArrayList using Java 8 Stream API...!!! Share on X
Example
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 | import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class RemoveDuplicatesFromListJava8 { public static void main(String[] args) { List <String> originalList = new ArrayList <String> (); originalList.add("yogi"); originalList.add("noni"); originalList.add("isha"); originalList.add("yogi"); originalList.add("pulkit"); originalList.add("noni"); originalList.add("noni"); System.out.println("Original List: \n" + originalList); List <String> listAfterDuplicatesRemoval = list.stream() .distinct() .collect(Collectors.toList()); System.out.println("\nList after duplicates removal: \n" + listAfterDuplicatesRemoval); } } |
Let’s try to understand the code:
1. Create a list and add duplicate elements into it.
1 2 3 4 5 6 7 8 9 | List < String > list = new ArrayList < String > (); list.add("yogi"); list.add("noni"); list.add("isha"); list.add("yogi"); list.add("pulkit"); list.add("noni"); list.add("noni"); |
2. Convert the list into ‘stream’
1 | list.stream() |
3. Extract the unique entries in the list with the use of ‘distinct’ method of stream
1 2 | list.stream() .distinct() |
4. Finally, Store the unique or distinct entries in to a collector
1 | collect(Collectors.toList()) |
Output:
1 2 3 4 5 | Original List: [yogi, noni, isha, yogi, pulkit, noni, noni] List after duplicates removal: [yogi, noni, isha, pulkit] |
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams