jdk1.8_03_流库——收集结果

本文通过实例演示了如何使用 Java 的 Stream API 进行数据处理,包括将对象流收集到 Map 中,处理本地化语言映射,以及解决国家方言集合的复杂数据结构问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 程序清单

public class CollectingIntoMaps {

public static class Person{
    private int id;
    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

    //创建流
    public static Stream<Person> people(){
        return Stream.of(new Person(1,"阿花"),new Person(2,"桂花"),new Person(3,"春花"));
    }

    public static void test(){
        Map<Integer,String> idToName=people().collect(Collectors.toMap(Person::getId,Person::getName));
        System.out.println("idToName:"+idToName);

        Map<Integer,Person> idToPerson=people().collect(Collectors.toMap(Person::getId, Function.identity()));
        System.out.println("idToPerson:"+idToPerson.getClass().getName()+": "+idToPerson);

        idToPerson=people().collect(Collectors.toMap(
                Person::getId,Function.identity(),(existringValue,newVlue)->{throw new IllegalStateException();
                }, TreeMap::new
                ));


    }
    //locale映射表存储不同国家的语言
    public static void localLanguage(){
        Stream<Locale> localeStream=Stream.of(Locale.getAvailableLocales());
        Map<String,String> languagestream=localeStream.collect(Collectors.toMap(
                Locale::getDisplayLanguage,
                l->l.getDisplayLanguage(l),
                (existringValue,newValue)->existringValue));
        System.out.println("language:"+languagestream);
    }

    //localLanguage,一个国家的方言的集合
    public static void  localLanguageCountry(){
        Stream<Locale> localeStream=Stream.of(Locale.getAvailableLocales());
        Map<String, Set<String>> languageStreamSets=localeStream.collect(Collectors.toMap(
                Locale::getDisplayCountry,//a
                l-> Collections.singleton(l.getDisplayLanguage()),//b
                (a, b)->{
                        Set<String> union=new HashSet<>(a);
                        union.addAll(b);
                        return union;
                }));
        System.out.println("localLanguageCountry"+languageStreamSets);
    }

    public static void main(String[] args) {
        test();
        localLanguage();
        localLanguageCountry();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值