java8 lamad表达式一些用法

用lamad写了几天业务代码,发现方便不少。
map可以理解成是对对象里面部分属性的提取或者加工转化

filter:过滤某些数据
collect:是输出指定的集合类型,比如
collect(Collectors.toMap(TestBean::getId,  Function.identity()))
collect(Collectors.groupingBy(TestBean::getName));

List的一些玩法

假设TestBean有以下属性
private int id ;
private int age;
private String name;
获取List里面到某些属性转化成新的List
List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
List<Integer> idList = list.stream().map(TestBean::getId).collect(Collectors.toList());
List<String> nameList = list.stream().map(TestBean::getName).collect(Collectors.toList());
List 转化成List
List<String>  stringList=Arrays.asList("1","2","3");
List<Integer> integerList = stringList.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());
根据条件过滤List
比如获取年龄大于18的集合
List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
List<TestBean> filterList = list.stream().filter(testBean -> testBean.getAge() > 18).collect(Collectors.toList());

  List<GradeBo> filterStatusGradeList = gradeList.getData().stream().filter(gradeBo -> filterByGradeStatus(gradeBo, request.getClassStatusList())
  ).collect(Collectors.toList());

  private boolean filterByGradeStatus(GradeBo gradeBo, List<Integer> classStatusList) {
          for (Integer classStatus : classStatusList) {
              switch (ClassStatusEnum.valueOf(classStatus)) {
                  case DEAFAULT:
                      return true;
                  //未入学
                  case NOT_ENROL:
                      return gradeBo.getGradeNumber().equals(0);
                  //入学
                  case ENROL:
                      return gradeBo.getGradeNumber() > 0 || gradeBo.getGradeNumber() < 100;
                  //毕业
                  case GRADUATE:
                      return gradeBo.getGradeNumber().equals(100);
              }
          }
          return false;
      }
List 里面某些数据聚合相加
相同名字的数据聚合,同时年龄相加
List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(TestBean::getName, Collectors.summingInt(TestBean::getAge)));
List 去重复
根据name去重复
List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
List<TestBean> distinctList = list.stream().filter(distinctByKey(TestBean::getName)).collect(Collectors.toList());
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
       Set<Object> seen = ConcurrentHashMap.newKeySet();
       return t -> seen.add(keyExtractor.apply(t));
   }
List 转Map>
  根据某个属性,将list转化成Map<String, List<TestBean>>
   List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
Map<String, List<TestBean>> map1 = list.stream().collect(Collectors.groupingBy(TestBean::getName));
Map<Integer, List<TestBean>> map2 = list.stream().collect(Collectors.groupingBy(TestBean::getId));
List 转Map
根据某个属性,将list转化成Map<String, TestBean>
 List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
Map<Integer, TestBean> map3 = list.stream().collect(Collectors.toMap(TestBean::getId, testBean -> testBean));
Map<Integer, TestBean> map4 = list.stream().collect(Collectors.toMap(TestBean::getId,  Function.identity()));
List处理里面对数据
比如对现有list里面对年龄都加1
List<TestBean> list = Arrays.asList(new TestBean(1,18, "ggj"), new TestBean(2,18, "ggj"), new TestBean(3,19, "ggj3"));
List<Integer> addAgeList = list.stream().filter(testBean -> testBean.getAge() > 18).map(s -> s.getAge() + 1).collect(Collectors.toList());

对map里面存在对ke 数据处理
List<QueryRefCountResult> queryRefCountResults = response.getResult();
            Map<String, QueryRefCountResult> map = queryRefCountResults.stream().collect(Collectors.toMap(QueryRefCountResult::getResourceId, Function.identity()));
            results.stream()
                    .filter(paperListResult -> map.containsKey(String.valueOf(paperListResult.getId())))
                    .forEach(paperListResult -> paperListResult.setPackageReferenceNum( Integer.valueOf(map.get(String.valueOf(paperListResult.getId())).getCount())));
        }

两个list 比较去除相同元素

List<QuestionOptionResult.Node> hiddenQuestionTypeList
   hiddenQuestionTypeList.forEach(hiddenQuestionType -> {
     questionTypeNodeList.removeIf(type -> type.getCode().equals(hiddenQuestionType.getCode()));
    });

list自定义排序

list=list.stream().sorted((v1,v2)->Long.compare(v1.getAge(),v2.getAge())).collect(Collectors.toList());

IntStream、DoubleStream和LongStream

0到9顺序循环
IntStream.range(0, 10).forEach(s -> System.out.println("range" + s));
0到10 并行循环
IntStream.rangeClosed(1, 10).parallel().forEach(i -> {System.out.println("rangeClosed 并行" + i); });

 List<String> itemList = IntStream.range(0, 10).mapToObj(i -> "item" + ThreadLocalRandom.current().nextInt(10)).collect(Collectors.toList());
 //Collectors.joining("") 其实就是将List<String>转为 String
  String PAYLOAD=IntStream.range(0, 10).mapToObj(i->"a").collect(Collectors.joining(""));

 List<Integer> itemList2 = IntStream.range(0, 10).map(i -> i + ThreadLocalRandom.current().nextInt(10)).boxed().collect(Collectors.toList());

//随机创建一个数组,然后转换成List<Item>
private static List<Item> createCart() {
      return IntStream.rangeClosed(1, 3)
              .mapToObj(i -> "item" + ThreadLocalRandom.current().nextInt(items.size()))
              .map(name -> items.get(name)).collect(Collectors.toList());
}

map list 一些用法

Map<String, List<String>> map = new HashMap<>();
List<String> list;

// 一般这样写
list = map.get("list-1");
if (list == null) {
    list = new LinkedList<>();
    map.put("list-1", list);
}
list.add("one");

// 使用 computeIfAbsent 可以这样写
list = map.computeIfAbsent("list-1", k -> new ArrayList<>()).add("one");

//例如
ConcurrentHashMap<String, List<UserDTO>> autoCompleteIndex = new ConcurrentHashMap<>();
        autoCompleteIndex.computeIfAbsent("a", s -> new ArrayList<>())
                .add(new UserDTO("d"));
        autoCompleteIndex.computeIfAbsent("a", s -> new ArrayList<>())
                .add(new UserDTO("c"));

装箱和拆箱

案例变量:menu为一个菜单列表(list),内含有name(名字)、calories(热量)、type(类型)属性。
   int calories = menu.stream()
            .mapToInt(Dish::getCalories)
            .sum()
//省去拆箱过程
boxed()是装箱过程

list里面是否存在某个元素

boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));
 subjectResultList.stream().anyMatch(s->s.getSubjectCode().equals(subjectCode)

逗号分割

String courseIds = packList.stream()
      .filter(e -> e.getCourse() != null)
      .map(PackageCourse::getCourseId).map(String::valueOf).distinct()
        .collect(Collectors.joining(","));