前言
合并两个list中的元素,返回一个不重复且有序(升序/降序)的list , 用Java实现。
以下是3种实现方式:
HashSet+Collections.sort ;
TreeSet ;
java8的stream流。
代码
import com.google.common.collect.Lists;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Classname merge
* @Description 合并两个list中的元素,返回一个不重复且有序的list
* @Author Author
* @Version 1.0
*/
public class merge {
public static void main(String[] args) {
List<Integer> listA = Lists.newArrayList(-1, -2, -5, -4, 1, 3, 5, 4);
List<Integer> listB = Lists.newArrayList(-9, -1, 2, 9, 7, 6);
//HashSet方式实现,hashSet去重,Collections.sort升序,Collections.reverse降序
operateByHashSet(listA, listB);
//TreeSet 方式实现: 既去重又排序,默认升序
operateByTreeSet(listA, listB);
// java 8 的stream 方式实现
operateByStream(listA, listB);
}
//HashSet方式实现,hashSet去重,Collections.sort升序,Collections.reverse降序
private static void operateByHashSet(List<Integer> listA, List<Integer> listB) {
//hashSet去重
List<Integer> listBySet = distinctByHashSet(listA, listB);
//排序(默认升序)
Collections.sort(listBySet);
System.out.println("listBySet升序排列:" + listBySet);
//降序
Collections.reverse(listBySet);
System.out.println("listBySet降序排列:" + listBySet);
}
//hashSet去重
private static List<Integer> distinctByHashSet(List<Integer> listA, List<Integer> listB) {
Set<Integer> set = new HashSet<>(listA);
set.addAll(listB);
System.out.println("set:" + set);
return new ArrayList<>(set);
}
//TreeSet 方式实现: 既去重又排序,默认升序
private static void operateByTreeSet(List<Integer> listA, List<Integer> listB) {
TreeSet<Integer> treeSet = new TreeSet<>(listA);
treeSet.addAll(listB);
//升序
System.out.println("treeSet升序排列:" + treeSet);
//降序
System.out.println("treeSet降序排列:" + treeSet.descendingSet());
}
// java 8 的stream 方式实现
private static void operateByStream(List<Integer> listA, List<Integer> listB) {
//升序
List<Integer> listByStream = Stream.of(listA, listB).flatMap(Collection::stream).distinct().sorted().collect(Collectors.toList());
System.out.println("listByStream升序排列:" + listByStream);
//降序
List<Integer> listByStreamDesc = Stream.of(listA, listB).flatMap(Collection::stream).distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("listByStreamDesc降序排列:" + listByStreamDesc);
}
运行结果:
备注:
List<Integer> listA = Lists.newArrayList(-1, -2, -5, -4, 1, 3, 5, 4);
List<Integer> listB = Lists.newArrayList(-9, -1, 2, 9, 7, 6);
以上listA和listB 的创建方式采用的guava的方法,需要在pom引入
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
</dependencies>
如果不用guava,用Jdk自带的方式如下:
// 用数组方式建list
Integer[] a={-1, -2, -5, -4, 1, 3, 5, 4};
List<Integer> listA = new ArrayList<>(Arrays.asList(a));
Integer[] b = {-9, -1, 2, 9, 7, 6};
List<Integer> listB = new ArrayList<>(Arrays.asList(b));
或
List listA = new ArrayList();
listA.add(-1);
listA.add(-2);
...
List listB = new ArrayList();
listB.add(-9);
listB.add(-1);
...