开发中简化代码之Java

Java基础

浏览数:138

2019-11-2

2018

1. 去除数组中的空值和null值,并返回新的数组

import org.apache.commons.lang3.StringUtils;

String[] users = {"", "jason", "bill", null, "rose"};
String[] tempUsers = Arrays.stream(users)
                .filter(StringUtils::isNotBlank)
                .toArray(String[]::new);

2. 拼接字符串,若字符串不为空则以空格隔开,为空则忽略(比如人的名称:firstName + middleName + lastName)

String firstName = "Jason"
String middleName = "";
String lastName = "Tang";

String userName = Joiner.on(" ").skipNulls().join(firstName.trim(), middleName.trim(), lastName.trim());

3. 判断集合中没有符合条件的对象(例:判断用户没有该角色)

List<Integer> integers = Arrays.asList(1, 2, 3);
for (Integer roleNum : roleNums) {
    if (userRoleList.stream().noneMatch(ur -> Objects.equals(roleNum, ur.getRoleNum()))) {
        System.out.print("roleNum = " + roleNum + "不存在")
    }
}

// anyMatch : 任意一个元素符合,返回true
// allMatch : 所有元素符合,才返回true
// noneMatch : 所有元素都不符合,才返回true

4. 将List集合转化为数组,将数组转化为字符串

List<Integer> itgs = new ArrayList<>();
itgs.add(1);
itgs.add(2);
itgs.add(3);
// 将集合转化为对应的对象数组
Integer[] itgArr = itgs.toArray(new Integer[0]);
// 将数组转化为字符串
String itgStr = Arrays.toString(itgArr);

System.out.println(itgStr);    // [1, 2, 3]
2019-03-04

5. 将Map按key进行排序和降序(value排序同理)

Map<String, Integer> map = new HashMap<>();
map.put("2018-10-12", 22);
map.put("2018-11-12", 22);
map.put("2018-09-12", 22);
map.put("2018-12-12", 22);
map.put("2018-07-12", 123);
map.put("2019-10-12", 55);
map.put("2019-07-12", 55);

// 降序
LinkedHashMap<String, Integer> ascLinkedHashMap = map.entrySet().stream()
      .sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
       (oldValue, newValue) -> newValue, LinkedHashMap::new));

// 升序
LinkedHashMap<String, Integer> descLinkedHashMap = map.entrySet().stream()
      .sorted(Map.Entry.comparingByKey())
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
       (oldValue, newValue) -> newValue, LinkedHashMap::new));

System.out.println(ascLinkedHashMap);
System.out.println(descLinkedHashMap);
持续更新…

作者:JasonDev