JAVA SE 8 的流库-1.9收集到映射表中

本文深入探讨了Java 8 Stream API中Collectors.toMap()方法的用法,包括如何创建映射表,处理键值冲突,以及如何在遇到重复键时合并值。同时,文章还介绍了如何通过提供自定义函数来解决键冲突问题,并展示了如何生成特定类型的映射表,如TreeMap。

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

1.9 收集到映射表中

Collectors.toMap方法有两个函数引元,他们用来产生映射表的键和值。

Map<Integer,String> idToName = people().collect(
			    Collectors.toMap(Person::getId, Person::getName));

通常情况下,值应该是实际的元素,因此第二个函数可以使用Function.identity()

java.util.function.Function是函数式接口,它的特点是有且只有一个抽象方法。
对于函数式接口,形如这样的表达式(x -> x + 1)能够实例化一个对象。
并且该表达式正是那个唯一的抽象方法的实现。(没有完全弄懂,留个?)
Map<Integer, Person> idToPerson = people().collect(
				Collectors.toMap(Person::getId, Function.identity()));

如果多个元素映射同一个键,那么就会存在冲突,收集器将会抛出一个IllegalStateException对象,可以提供第三个引元来覆盖这种行为。

Map<String,String> languageNames = locales.collect(
				Collectors.toMap(Locale::getDisplayLanguage, 
				l->l.getDisplayLanguage(),
				(existingValue,newValue)->existingValue));

如果一个键对应多个值时,需要一个Map<String,<Set < String > >。将已有集和新集做并操作。

Map<String,Set<String>> countryLanguageSets = locales.collect(
				Collectors.toMap(Locale::getDisplayCountry, 
				l->Collections.singleton(l.getDisplayLanguage()),
				(a,b)->{//union of a and b 
					Set<String> union = new HashSet<>(a);
					union.addAll(b);
					return union;
				}));

如果想要得到TreeMap,可以将构造器作为第四个引元来提供,需要提供一种合并函数。

idToPerson = people().collect(
				Collectors.toMap(Person::getId, Function.identity(),(
						existingValue,newValue)->{throw new IllegalStateException();//????
						},TreeMap::new));
package JavaSE8的流库;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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 String getName()
		{
			return name;
		}
		
		public String toString()
		{
			return getClass().getName()+"[id="+id+",name="+name+"]";
		}
	}
	
	public static Stream<Person> people()
	{
		return Stream.of(new Person(1001,"Peter"), 
				new Person(1002,"poul"), new Person(1003,"Mary"));
	}
	
	public static void main(String[] args)throws IOException {
		// TODO 自动生成的方法存根

		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(),(
						existingValue,newValue)->{throw new IllegalStateException();//????
						},TreeMap::new));
		System.out.println("idToPerson:"+idToPerson.getClass().
				getName()+idToPerson);
		
		Stream<Locale> locales = Stream.of(Locale.getAvailableLocales());
		Map<String,String> languageNames = locales.collect(
				Collectors.toMap(Locale::getDisplayLanguage, 
				l->l.getDisplayLanguage(),
				(existingValue,newValue)->existingValue));
		System.out.println("languageNames:"+languageNames);
		
		locales = Stream.of(Locale.getAvailableLocales());
		Map<String,Set<String>> countryLanguageSets = locales.collect(
				Collectors.toMap(Locale::getDisplayCountry, 
				l->Collections.singleton(l.getDisplayLanguage()),
				(a,b)->{//union of a and b 
					Set<String> union = new HashSet<>(a);
					union.addAll(b);
					return union;
				}));
		System.out.println("countryLanguageSets:"+countryLanguageSets);
	}

}

输出结果:
在这里插入图片描述
(如有问题,请评论!Thanks♪(・ω・)ノ)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值