Java8 函数式编程有意思的写法

函数式编程有意思的写法

1、collect相关

字符串拼接

List<Sring> menu = new ArrayList<Sring>();
String shortMenu = menu.stream().collect(Collectors.joining(","));

// 对象list转换为字符串ist
List<String> shopIdList = resultList.parallelStream().map(n -> 
n.getShopId()).collect(Collectors.toList());

// 排序
Collections.sort(tableData, Comparator
.comparing(ShopActivityRateDTO::getActivityRate, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(ShopActivityRateDTO::getNodeCode, Comparator.naturalOrder()));

// list转map
Map<String, TbShopTagRelationDTO> activeTagShopMap = activeTagShopList.parallelStream().collect(Collectors.toMap(TbShopTagRelationDTO::getShopId, Function.identity(), (oldValue, newValue) -> newValue));

Map<String, String> branchCodeAreaNameMap = branchCompanyOfSuperNodeList.parallelStream().collect(HashMap::new, (m, v) -> m.put(v.getBranchCompanyCode(), v.getRegionName()), 
HashMap::putAll);

2、‘尾-递’阶乘

static long factorialTailRecurive(long n) {
    return factorialHelper(1, n);
}

static long factorialHelper(long acc, long n) {
    return n == 1 ? acc : factorialHelper(acc * n, n-1);
}

3、reduce 相关操作

查看列表中的最大值

Option<Integer> max = numbers.stream().reduce('Integer::max);
Option<Integer> max = numbers.stream().reduce('Integer::min);

元素求和/机

int product = numbers.stream().reduce(0, (a , b) -> a + b);
int product = numbers.stream().reduce(1, (a , b) -> a * b);

阶乘

static long factorialTailRecurive(long n) {
    return LongStream.rangeClosed(1, n).reduce(1, (long a, long b) -> a * b);
}

4、Optional相关

串联获取属性

person.flatMap(Person::getCar)
         .flatMap(Car::gerInsurance)
         .map(Insurance::getName)
         .orElse("Unkonwn");

HashMap 根据 value 排序

// creating HashMap
Map<String, Integer> namesAges = new HashMap<>();
 
 // storing the values
namesAges.put("Hari", 35);
namesAges.put("Jhon", 30);
namesAges.put("Jakey", 50);
namesAges.put("kane", 45);
 
Map<String, Integer> sortByValueMap = namesAges.entrySet().stream().sorted(Entry.comparingByValue())
         .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(),
                        (entry1, entry2) -> entry2, LinkedHashMap::new));

Map<String, Integer> sortedMapInDescending = namesAges.entrySet()
         .stream()
         sorted(Collections.reverseOrder(Entry.comparingByValue()))
         .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(),
                    (entry1, entry2) -> entry2, LinkedHashMap::new));