Collectors流编程相关代码题

2021/5/24 12:25:14

本文主要是介绍Collectors流编程相关代码题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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+" ");
        }
    }
}

 



这篇关于Collectors流编程相关代码题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程