编程语言
首页 > 编程语言> > Java8使用Stream将List转为Map的注意点

Java8使用Stream将List转为Map的注意点

作者:互联网

 昨天QA同事给我提了一个Bug,后台配置的顺序跟浏览器展示页面的顺序不一致,感觉莫名其妙,于是进行debug追踪,模拟代码如下:

public class Example {


	private Long id;

	private String desc;


	public Long getId() {
		return id;
	}

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

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@Override
	public String toString() {
		return "Example{" +
				"id=" + id +
				", desc='" + desc + '\'' +
				'}';
	}
}
public class Test {


	public static void main(String[] args) {

		List<Example> list = new ArrayList<>();

		for (long i = 1; i <=5; i++) {
			Example example = new Example();
			example.setId(new Random().nextLong());
			example.setDesc(String.valueOf(example.getId()));
			list.add(example);
		}

		list.forEach(System.out::println);


		System.out.println("====================");


		Map<Long, List<Example>> id2ExaMap = list.stream().collect(Collectors.groupingBy(Example::getId));

		id2ExaMap.forEach((id,example)->{
			System.out.println("id:" + id + " ,example" + example);
		});
	}
}

运行main方法后,控制台输出如下:
20211231153732

于是我的bug就诞生了。上网查了一下,解释如下:

image-20211231164204377

链接在这里

所以为了解决顺序问题,可以使用LinkedHashMap来进行接收。

public class Test {


	public static void main(String[] args) {
		List<Example> list = new ArrayList<>();

		for (long i = 1; i <=5; i++) {
			Example example = new Example();
			example.setId(new Random().nextLong());
			example.setDesc(String.valueOf(example.getId()));
			list.add(example);
		}

		list.forEach(System.out::println);


		System.out.println("====================");

		//这里使用LinkedHashMap来进行接收
		LinkedHashMap<Long, List<Example>> id2ExaMap = list.stream()
		.collect(Collectors
		.groupingBy(Example::getId, LinkedHashMap::new, Collectors.toList()));

		id2ExaMap.forEach((id,example)->{
			System.out.println("id:" + id + " ,example" + example);
		});
	}
}

运行main方法,控制台输出如下:

image-20211231172129326

标签:Map,String,Stream,List,public,example,id2ExaMap,id,desc
来源: https://www.cnblogs.com/reecelin/p/16074705.html