- List
转 String 字符串用逗号分割
普通方式
List<Long> useridList = authoritativeVO.getUserList();
int count = 0;
StringBuilder targetStr = new StringBuilder();
for(int i=0;i<useridList.size();i++){
targetStr.append(useridList.get(i));
count++;
if(count<useridList.size()){
targetStr.append(",");
}
}
System.out.println(targetStr.toString());
lambda方式
String deptIds = authoritativeVO.getUseridList().stream().map(i -> String.valueOf(i)).collect(Collectors.joining(","));
- 查询18岁学生的id列表
##1.查询18岁的学生列表
List<Student> studentList = studentService.list(Wrappers.<Student>lambdaQuery().eq(Student::getAge,18);
##2.普通方式获取18岁学生列表的id
List<Long> idList = new ArrayList<>();
for(Student stu : studentList){
idList.add(stu.getId());
}
##2.lambda获取18岁学生列表的id
List<Long> ids = studentList.stream().map(Student::getId).collect(Collectors.toList());
- List 转Map
//list 转map
普通方式
Map<String,Person> map = new HashMap<>();
for (Person person:list) {
map.put(person.getName(),person);
}
lambda方式
Map<String,Person> map1 = list.stream().collect(Collectors.toMap(Person::getName, t->t));
Map<String,Address> map2 = list.stream().collect(Collectors.toMap(Person::getName, t->t.getAddress()));
Map<String,Integer> map4 = list.stream().collect(Collectors.toMap(Person::getName, t->t.getAge()));
Map<String,Integer> map3 = list.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
- List 分组
普通方式
Map<Integer,List<Person>> mapt = new HashMap<>();
for (Person person:list){
if(mapt.containsKey(person.getAge())){
List<Person> people = mapt.get(person.getAge());
people.add(person);
}else{
List<Person> people = new ArrayList<>();
people.add(person);
mapt.put(person.getAge(),people);
}
}
lambda方式
Map<Integer,List<Person>> listMap = list.stream().collect(Collectors.groupingBy(Person::getAge));
- Map 转 List
List collect = listMap.values().stream().collect(Collectors.toList());
- 过滤
List<String> stringList = list.stream().map(s -> s.getName()).filter(s -> !s.isEmpty()).collect(Collectors.toList());
List<Person> personList = list.stream().filter(s -> !s.getName().isEmpty()).collect(Collectors.toList());
- 所使用的JAVA测试类如下
@Data
@Accessors(chain = true)
@AllArgsConstructor
public class Address {
private String province; //省
private String city; //市
private String county; //县
}
@Data
@Accessors(chain = true)
@AllArgsConstructor
public class Person {
private String name;
private int age;
private Address address;
}
标签:stream,Collectors,Person,List,逼格,list,collect,表达式,lambda
From: https://www.cnblogs.com/sansyou/p/17534004.html