[Java]Stream用法

BitVortexPro
• 阅读 1604
  1. 将list转为map

    Map<Long, ItemTO> itemMap =
        items.stream().collect(Collectors.toMap(ItemTO::getEventId, Function.identity(), (v1, v2)->v1));
  2. List中对象的某个属性值拿出来作为一个list
// 去重
List<Long> ids = items.stream().map(ItemTO::getId).distinct().collect(Collectors.toList());

// 不去重
List<Long> ids = items.stream().map(ItemTO::getId).collect(Collectors.toList());
  1. 将list转为Map<Long, List>
Map<Long, List<ItemTO>> itemListMap = itemList.stream().collect(Collectors.groupingBy(item -> item.getId()));

Map<Long, ItemTO> itemMap =
        items.stream().collect(Collectors.toMap(ItemTO::getEventId, Function.identity(), (v1, v2)->v1));
  1. 将list中的string转为long
List<Long> idList = groupList.stream().map(group->Long.parseLong(group.getGroupLeaderId())).collect(Collectors.toList());
  1. 过滤操作
groupIdList.stream().filter(x -> x!=null).collect(Collectors.toList());


List<Long> allPlatformIids = allStoreItemIndexResultTOS.stream().filter(t -> StoreItemTypeEnum.PLATFORM.getType()
      .equals(t.getType())).map(StoreItemIndexResultTO::getIid).collect(Collectors.toList());

//过滤采购数量为0的sku
List<ObmSkuInfoTO> skuCollectList = skuInfoTOList.stream().
        filter(e -> e.getNum() > 0).collect(Collectors.toList());


/**
 * 在订单列表中过滤指定的oid
 * @param effectiveLists
 * @param oid
 * @return
 */
private List<ItemTO> filterOrder(List<ItemTO> itmeList, long oid) {
    return itmeList.stream().filter(p -> {
        if (p.getOid().equals(oid)) {
            return false;
        }
        return true;
    }).collect(Collectors.toList());
}
  1. 将list中对象的两个属性值分别作为map的key和value
itemList.stream().filter(t -> t.getId() != null)
        .collect(Collectors.toMap(ItemTO::getId, ItemTO::getName, (k1, k2)->k2));
  1. 对list做操作
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());

// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());

// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());

// 并集
List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
listAll.addAll(listAll2);

// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重并集 listAllDistinct---“);

// 循环输出
listAllDistinct.parallelStream().forEachOrdered(System.out :: println);
  1. map的操作,移除
// 通过value移除
map.values().removeIf(value -> !value.contains("1"));

// 通过key移除
map.keySet().removeIf(key -> key != 1);

// key或者value移除
map.entrySet().removeIf(entry -> entry.getKey() != 1);
  1. 排序操作
// 升序
itemList = itemList.stream().sorted(Comparator.comparingInt(ItemTO::getPtPrice)).collect(Collectors.toList());
// 降叙
itemList = itemList.stream().sorted(Comparator.comparingInt(ItemTO::getPtPrice).reversed()).collect(Collectors.toList());
  1. groupBy操作

//a
Map<Long,List<Long>> exhibitionPitemMap = list.stream().collect(Collectors.groupingBy(TestDTO1::getLevle1CategoryId, Collectors.mapping(TestDTO1::getPitemId, Collectors.toList())));
//b
Map<Long, List<TestDTO2>> categoryPitemMap = list.stream().collect(Collectors.groupingBy(TestDTO2::getLevle1CategoryId));
  1. map转list用法
Map<String, String> map = new HashMap<>(); 
// Convert all Map keys to a List
List<String> result = new ArrayList(map.keySet()); 

// Convert all Map values to a List
List<String> result2 = new ArrayList(map.values()); 

// Java 8, Convert all Map keys to a List
List<String> result3 = map.keySet().stream() .collect(Collectors.toList());

// Java 8, Convert all Map values to a List
List<String> result4 = map.values().stream() .collect(Collectors.toList());

// Java 8, seem a bit long, but you can enjoy the Stream features like filter and etc.
List<String> result5 = map.values().stream() .filter(x -> !"apple".equalsIgnoreCase(x)) .collect(Collectors.toList());
  1. 修改list中的元素值
list.stream().filter(a -> 筛选条件).forEach(b -> b.setOrg("1"));
  1. 将list中元素的两个属性分别作为map的key和value

    Map<Long, String> idNameMap = userList.stream().collect(Collectors.toMap(UserDO::getId, UserDO::getName, (v1, v2)->v1));
  2. 将map中的key从String转换成Long
Map<Long, ItemTO> map1 = map.entrySet().stream().collect(Collectors.toMap(e -> Long.parseLong(e.getKey()), Map.Entry::getValue));
  1. foreach中做查询操作
List<UserTO> userList = userList.stream().filter((userTO) -> {

      ClassTO classTO = classManager.getClassById(userTO);
      return classTO.getStatus() != null && classTO.getStatus() > 0;
}).collect(Collectors.toList());
  1. 使用方法生成key
Map<String, UserTO> uidMap = userList.stream().collect(toMap(UserUtil::getKeyByUser, Function.identity(), (m1, m2) -> m1));  
public static String getKeyByUser(UserTO userTO) {
    return Joiner.on(Constant.UNDERLINE).join(userTO.getId(), userTO.getName());
}
  1. 对于最小的元素进行重新赋值
userList.stream().min(Comparator.comparingLong(UserTO.getAge)).ifPresent(e->e.setShow(true));
  1. 将list拼接成string
classTO.setName(userList.stream().map(String::valueOf).collect(joining(Constant.COMMA))); 
  1. 过滤出level>xx的元素

    List<UserTO> = userList.stream().filter(u -> u.getLevel() > 2).collect(Collectors.toList());
点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
3年前
java8新特性
Stream将List转换为Map,使用Collectors.toMap方法进行转换背景:User类,类中分别有id,name,age三个属性。List集合,userList,存储User对象1、指定keyvalue,value是对象中的某个属性值。 Map<Integer,StringuserMap1userList.str
Stella981 Stella981
3年前
List的Select 和Select().tolist()
List<PersondelpnewList<Person{newPerson{Id1,Name"小明1",Age11,Sign0},newPerson{Id2,Name"小明2",Age12,
Wesley13 Wesley13
3年前
Java8并行http请求加快访问速度
背景1.通常我们在获取到一个list列表后需要一个挨着一个的进行遍历处理数据,如果每次处理都需要长时间操作,那整个流程下来时间就是每一次处理时间的总和。2.Java8的stream接口极大地减少了for循环写法的复杂性,stream提供了map/reduce/collect等一系列聚合接口,还支持并发操作:parallelStream。例子
Wesley13 Wesley13
3年前
JAVA常用编程代码块
转Map时要考虑Map的key是否重复List<Entity转为Map<keyField,valueField将一个List实体集合转换为以Entity某一个字段为key,另一字段为value映射的Map/
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
Java8 Stream分组
//根据排课id分组Map<Integer,List<Schedule4HomeworkidSchedule4HomeworksMapschedule4Homeworks.stream().collect(Collectors.groupingBy(Schedule4Homework::getScheduleId));
Wesley13 Wesley13
3年前
Java8的自定义收集器与并行
Lambda表达式是Java8最重要的新特性,基础的内容这里就不说了,让我们从收集器开始。什么是收集器就是用于收集流运算后结果的角色。例如:List<String collect  list.stream().map(TestBean::getName).collect(Collectors.toList());以上
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
卜哥歌 卜哥歌
10个月前
[JAVA的写法]之List的stream()操作
List里的遍历pmDesignFilespmDesignFiles.stream().map((m)m.setLocalPath(“234234”);returnm;).collect(Collectors.toList());List分组MapengM
美凌格栋栋酱 美凌格栋栋酱
4个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
BitVortexPro
BitVortexPro
Lv1
蓟城通漠北,万里别吾乡。
文章
3
粉丝
0
获赞
0