欢迎光临
感受代码之美

Java 8新特性使用示例

本文整理了,在平时的开发过程中尝试使用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

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

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)

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"));
}

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));
转载请注明来源:四个空格 » Java 8新特性使用示例

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址