1、序列去重
使用现成函数
import java.util.*; import java.util.stream.Collectors; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()); List<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++){ list.add(sc.nextInt()); } list = list.stream() .distinct() .collect(Collectors.toList()); for(int j:list){ System.out.print(j+" "); } } }
另外:使用集合的特性--LinkedHashSet+打印时转字符串
import java.util.*; import java.util.stream.Collectors; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()); Set<String> set = new LinkedHashSet<>(); for(int i=0;i<n;i++){ set.add(Integer.toString(sc.nextInt())); } String s = set.stream().collect(Collectors.joining(" ")); System.out.println(s); } }
2、删除指定的数
import java.util.*; import java.util.stream.Collectors; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()); List<String> list = new ArrayList<>(); for(int i=0;i<n;i++){ list.add(Integer.toString(sc.nextInt())); } String value = Integer.toString(sc.nextInt()); list = list.stream() .filter(e->!e.equals(value)) .collect(Collectors.toList()); String s = list.stream() .collect(Collectors.joining(" ")); System.out.println(s); } }
3、
去重并排序
import java.util.*; import java.util.stream.Collectors; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++){ list.add(sc.nextInt()); } list = list.stream() .distinct() .collect(Collectors.toList()); Collections.sort(list); for(int j:list){ System.out.print(j+" "); } } }
方法2:使用Collectors的方法
import java.util.*; import java.util.stream.Collectors; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++){ list.add(sc.nextInt()); } list = list.stream() .distinct() .sorted() .collect(Collectors.toList()); for(int j:list){ System.out.print(j+" "); } } }