一点一滴记录 Java 8 stream 的使用

4 篇文章 2 订阅

日常用到,一点一滴记录,不断丰富,知识积累,塑造自身价值。欢迎收藏

String 转 List

String str = "1,2,3,4";
List<Long> lists = Arrays.stream(str.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

List 转 String

list.stream().map(String::valueOf).collect(Collectors.joining(","))

List<> 转 List<String> 或 Set<> 转 List<String>

list.stream().map(x -> x + "").collect(Collectors.toList())

List<> 对象获取某个值 转为 Long[] , String[] , Integer[]

基本类型:
List<Long> list = new ArrayList<Long>();  
list.add(1L);
list.add(2L);
list.add(3L);

Long[] l = list.stream().toArray(Long[]::new)
String[] s = list.stream().toArray(String[]::new)
Integer[] in = list.stream().toArray(Integer[]::new)

对象形式:
List<Long> list = new ArrayList<Long>();

ScheduleJobEntity sc = new ScheduleJobEntity()
sc.setId(1)
list.add(sc);

sc = new ScheduleJobEntity()
sc.setId(2)
list.add(sc);

sc = new ScheduleJobEntity()
sc.setId(3)
list.add(sc);

Long[] l = list.stream().map(ScheduleJobEntity::getId).toArray(Long[]::new)
String[] s = list.stream().map(ScheduleJobEntity::getId).toArray(String[]::new)
Integer[] in = list.stream().map(ScheduleJobEntity::getId).toArray(Integer[]::new)

List<> 对象获取某个值 转为 list<Long>

List<itemsBeans> = new ArrayList();
List<Long> items = itemsBeans.stream().map(ItemsBean::getItemid).collect(Collectors.toList());

Set 转 List

Set<Long> sets = xxx
List<Long> hids =  sets.stream().collect(Collectors.toList());

List 转 Map<Long, String>

List<Hosts> hosts = xxxx
Map<Long, String> hostMap = hosts.stream().collect(Collectors.toMap(Hosts::getHostid,Hosts::getName,(oldValue, newValue) -> newValue));

 List 转 Map<Long, Object>

List<ItemTriggerGroupByName> hosts = xxxx
Map<Long, ItemTriggerGroupByName> appsMap= apps.stream().collect(Collectors.toMap(ItemTriggerGroupByName::getHostId, e -> e , (oldValue, newValue) -> newValue));

 List 分组 转 Map<Long, List<Object>>

############ 无序的列表 #########
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

############ 有序的列表 #########
/**

groupingBy有三个参数,第一个参数就是key的Function了,第二个参数是一个map工厂,也就是最终结果的容器,一般默认的是采用的HashMap::new,最后一个参数很重要是一个downstream,类型是Collector,也是一个收集器,那就是说,这三个参数其实就是为了解决分组问题的
第一个参数:分组按照什么分类
第二个参数:分组最后用什么容器保存返回
第三个参数:按照第一个参数分类后,对应的分类的结果如何收集
其实一个参数的Collectors.groupingBy方法的 ,第二个参数默认是HashMap::new, 第三个参数收集器其实默认是Collectors.toList

所以HashMap是无序的大家都是知道的,所以原因找到了。
**/
建议使用以下 
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId,LinkedHashMap::new, Collectors.toList()));

List<Map<String,Object>> 转 Map<String,Object>

List<Map<String, Object>> ma = xxx

Map<String, Object> mapResource = ma.stream().map(Map::entrySet).flatMap(Set::stream).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue));

取map的字段
ma.stream().collect(Collectors.toMap(p -> { return p.get("code")+"";}, p -> { return p.get("value")+"";}

转化 再改变 key 
ma.stream().map(Map::entrySet).flatMap(Set::stream).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> { return v1 + "," + v2; }))


List 求和,最小,最大值,平均值获取

单数组类型

List<int> strs = Arrays.asList(34,5,1,76,23);
最小值
strs .stream().min(Comparator.comparing(Function.identity())).get();
最大值
strs .stream().max(Comparator.comparing(Function.identity())).get();


对象数组类型
int sum = empList.stream().mapToInt(Employee::getAge()).sum();
int max = empList.stream().mapToInt(Employee::getAge()).max().getAsInt();
int min = empList.stream().mapToInt(Employee::getAge()).min().getAsInt();
double avg = empList.stream().mapToInt(Employee::getAge()).average().getAsDouble();
System.out.println("最大值:"+max+"\n最小值:"+min+"\n总和:"+sum+"\n平均值:"+avg);

对 list 对象以某元素分组,进行多列,多字段,多元素分别求和

class Invoice {
	String name;
	Integer price;
	Integer originalPrice;
	Integer salePrice;

	public Invoice(String name, Integer price, Integer originalPrice, Integer salePrice) {
		super();
		this.name = name;
		this.price = price;
		this.originalPrice = originalPrice;
		this.salePrice = salePrice;
	}

	public String getName() {
		return name;
	}

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

	public Integer getPrice() {
		return price;
	}

	public void setPrice(Integer price) {
		this.price = price;
	}

	public Integer getOriginalPrice() {
		return originalPrice;
	}

	public void setOriginalPrice(Integer originalPrice) {
		this.originalPrice = originalPrice;
	}

	public Integer getSalePrice() {
		return salePrice;
	}

	public void setSalePrice(Integer salePrice) {
		this.salePrice = salePrice;
	}

}
public static void main(String[] args) {
		List<Invoice> list = Arrays.asList(new Invoice("I1001", 99, 95,85),
				new Invoice("I1001", 100, 101,110),
				new Invoice("I1002", 720, 750,770),
				new Invoice("I1003", 40, 50,60),
				new Invoice("I1003", 40, 50,70),
				new Invoice("I1004", 10, 15,12));
		List<Invoice> result = list.stream()
				// 表示id为key, 接着如果有重复的,那么从Invoice对象o1与o2中筛选出一个,这里选择o1,
				// 并把id重复,需要将nums和sums与o1进行合并的o2, 赋值给o1,最后返回o1
				.collect(Collectors.toMap(Invoice::getName, a -> a, (o1, o2) -> {
					o1.setPrice(o1.getPrice() + o2.getPrice());
					o1.setOriginalPrice(o1.getOriginalPrice() + o2.getOriginalPrice());
					o1.setOriginalPrice(o1.getSalePrice() + o2.getSalePrice());
					return o1;
				})).values().stream().collect(Collectors.toList());
		System.err.println(JSON.toJSONString(result));

	}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值