Original: https: //my.oschina.net/jack90john/blog/1493170
Many times the work will need to merge two List and remove duplicate content. This is a very simple operation, here is mainly the record about to complete this operation by using Stream.
Before java8 more conventional approach is to add two to a Set List, because the content Set of unrepeatable, it will automatically go heavy, then turn the Set List, the following code:
Set<String> set = new HashSet<>(listA); set.addAll(listB); List<String> list = new ArrayList<>(set); System.out.println(list);
list after the merger and to do so is the result of heavy.
After java8 happens, we have a more convenient and efficient approach is to help us complete this operation by Stream, code is as follows:
List<String> collect = Stream.of(listA, listB)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
The results thus obtained final results we want, you can clearly see the finished code via Stream looks more simple and smooth.
Tips: If you want to merge is subject Please note that override equals and hashcode methods.
Attachment:
Complete code, for reference.
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Combine { public static void main(String[] args) { String[] arr1 = {"a", "b", "c", "d", "e", "f"}; List<String> listA = new ArrayList<>(Arrays.asList(arr1)); String[] arr2 = {"d", "e", "f", "g", "h"}; List<String> listB = new ArrayList<>(Arrays.asList(arr2)); Set<String> set = new HashSet<>(listA); set.addAll(listB); List<String> list = new ArrayList<>(set); System.out.println(list); List<String> collect = Stream.of(listA, listB) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); System.out.println(collect); } }