Java 8新特性使用示例

洼地云 tuoyidashi.png

本文整理了,在平时的开发过程中尝试使用Java 8简化代码量的几个示例,不断学习补充中。

1.List<Map>转为List<String>

    /**
     * 转换:List<Map>转List<String>
     *
     * @return
     */
    public void convertToList() {
        List<Map> mapList = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < 5; i++) {
            map = new HashMap<>();
            map.put("BLOG_NAME", i + "个空格");
            mapList.add(map);
        }
        List<String> blogNameList = mapList.stream().map(s -> (String) s.get("BLOG_NAME")).collect(Collectors.toList());
        blogNameList.forEach(System.out::println);
    }

2.List<Object> 获取Object(filter)

    /**
     * 转换:List<Map>转Map
     *
     * @return
     */
    public void convertToList() {
        List<Map> mapList = new ArrayList<>();
        Map<String, Object> map;
        for (int i = 0; i < 5; i++) {
            map = new HashMap<>();
            map.put("BLOG_NAME", i + "个空格");
            mapList.add(map);
        }
        Map<String, Object> fourSpaces = mapList.stream()                        // Convert to steam
                .filter(x -> "4个空格".equals(x.get("BLOG_NAME")))        // we want "4个空格" only
                .findAny()                                      // If 'findAny' then return found
                .orElse(null);
        System.out.println(fourSpaces.get("BLOG_NAME"));
    }

3.获取Map的第一个元素key值

//if order is important, e.g. with a TreeMap/LinkedHashMap
map.entrySet().stream().findFirst();

//if order is not important or with unordered maps (HashMap...)
map.entrySet().stream().findAny();

4.Collectors.toMap用法

用法示例1:将Java List转为Map

Map<String, Long> result = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites));

用法示例2:将Java List转为Map

List<GraphNode> graphNodeList = new ArrayList<>();
Map<String, Object> nodesIdMap = graphNodeList.stream().collect(Collectors.toMap(GraphNode::getId, s -> s));

用法示例3:将Java List转为Map

List<PubOrganStaff> allStaffs = selectByExample(example);
Map identityInfoMap = allStaffs.stream().collect(Collectors.toMap(s -> s.getOrganId() + "#" + s.getExtType(), PubOrganStaff::getExtValue));

5.List<String>转String

String country;

List<String> cities = new ArrayList<>();
cities.add("Delhi");
cities.add("New York");
cities.add("Beijing");
cities.add("1kjh1231");

country = cities.stream()
                    .filter( c -> c.equals("Beijing"))
                    .findAny()
                    .map(v -> "China")
                    .orElse(null);
System.out.println(country);

6.平均值(average)

https://stackoverflow.com/questions/10791568/calculating-average-of-an-array-list

OptionalDouble average = marks
            .stream()
            .mapToDouble(a -> a)
            .average();

return average.isPresent() ? average.getAsDouble() : 0; 

7.排序(sorted)

示例1:按照字段排序

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

Map<String,String> map = new HashMap<>();
map.put("userid","JJ05");
list.add(map);

map = new HashMap<>();
map.put("userid","JJ02");
list.add(map);

map = new HashMap<>();
map.put("userid","JJ04");
list.add(map);

map = new HashMap<>();
map.put("userid","JJ01");
list.add(map);

list = list.stream().sorted(Comparator.comparing(o->o.get("userid"))).collect(Collectors.toList());

for(Map<String,String> m :list){
    System.out.println(m.get("userid"));
}

示例2: 按照时间逆序排列

Collections.sort(resultlist, Comparator.comparing(o -> {
            try {
                return DateTool.parseDatetime((String) ((Map) o).get("procEndTime"), "yyyyMMdd HH:mm:ss");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        }).reversed());

8.过滤(filter)

过滤符合条件的元素

List<SrItemsStandard> srItemsStandardList = new ArrayList<>();
SrItemsStandard standard = new SrItemsStandard();
standard.setCycles("1,2,3");
srItemsStandardList.add(standard);

standard = new SrItemsStandard();
standard.setCycles("2,3");
srItemsStandardList.add(standard);

standard = new SrItemsStandard();
standard.setCycles("1,3");
srItemsStandardList.add(standard);

srItemsStandardList = srItemsStandardList.stream().filter(s-> StringUtils.contains(s.getCycles(),"2")).collect(Collectors.toList());

System.out.println(srItemsStandardList.size()); // 2

9.分组(groupingBy)

Map<String, List<Student>> result = list.stream().collect(Collectors.groupingBy(Student::getAge));

10.Collectors.toSet()用法

List<Map> applyDsInfoList = queryApplyDsInfoService.queryApplyDsInfoForApplyObject(parameters);
Set<String> dsIdSet = applyDsInfoList.stream().map(s -> (String) s.get("DS_ID")).collect(Collectors.toSet());

11.Collectors.joining()用法

List<String> list = Arrays.asList("1","2","3");
String s = list.stream().collect(Collectors.joining(",")); // 1,2,3
赞(0)
未经允许禁止转载:优米格 » Java 8新特性使用示例

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册