1、提取list集合中bean的某一属性
List<Integer> uniqueList = result.stream().map(ComplaintsPdMappingSource::getSourceId).distinct().collect(Collectors.toList());
2、判断某一个值是否存在list集合中:
/**
* 转换字符串为bool
* 只有T或者true才返回true,其它返回false
*/
public static boolean anyEquals(final String strValue, final String... args){
Predicate<String> condtion = s -> strValue.equalsIgnoreCase(s);
List<String> list = Lists.newArrayList(args);
return list.stream().anyMatch(condtion);
}
3、如果orderTypeList等于null,那么返回一个初始化为10的集合
orderTypeList = Optional.of(orderTypeList).orElse(Lists.newArrayListWithCapacity(ConstVars.NUMBER_10));
4、将一个List集合以某一个字符串拼接成一个字符串:
eg: 集合{1,2,3}以,拼接后是1,2,3
ccUsers = lists.stream().collect(Collectors.joining(";"));
5、将一个List集合以某一个字段排序,并返回第一个:
Object c = list.stream().sorted(Comparator.comparing(User::getname())).findFirst().get();
6、将一个Map以key排序,返回一个新的map;
Map<String, String> newMap = maps.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
7、将一个List集合中以bean的某一个属性进行去重:
List<User> complaintsResult = List.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new));
8、将一个List集合中以bean的某一个属性排序:
result.stream().sorted((user u1, EventOperationInfo u2) -> u1.getAge().compareTo(u2.getAge()));
9、在一个List集合中求bean中某一个属性的最大的bean;
categoryIds.stream().max((e1, e2)-> e2.getLevel().compareTo(e1.getLevel())).get().getCategoryName();
10、对一个lis集合中所有bean的某一个属性求和
BigDecimal totalAmount = complaintsRefunds.stream().map(s -> s.getRefundAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
11、将多个集合转换为一个集合:
Stream<List<Integer>> stream = Stream.of(
Arrays.asList(1),
Arrays.asList(2,3),
Arrays.asList(4,5,6)
);
Stream<Integer> result = stream.flatMap((s) ->s.stream());
System.out.println(result.collect(Collectors.toList()));
12、list中按照某一个对象排序:
12.1:升序
result.stream().sorted(Comparator.comparing(EmailNotifyLogEntity::getCreateTime)).collect(Collectors.toList())
12.2:降序
result.stream().sorted(Comparator.comparing(EmailNotifyLogEntity::getCreateTime).reversed()).collect(Collectors.toList())
13、集合中套集合,怎么取得里面集合中的某一个属性的集合:例如List<List<User>>,怎么获取List<User>:
List<User> orderParticipants = Users.stream().flatMap(item -> item.stream()).collect(Collectors.toList());
14、java1.7以上迭代Map:
Map<String, String> map = Maps.newHashMap();
map.entrySet().stream().forEach(entry ->{
entry.getKey();
entry.getValue();
});
15、使用Optional判空:
User user = ...
if (user != null) {
String userName = user.getUserName();
if (userName != null) {
return userName.toUpperCase();
} else {
return null;
}
} else {
return null;
}
替换为以下代码
User user = ...
Optional<User> userOpt = Optional.ofNullable(user);
return userOpt.map(User::getUserName)
.map(String::toUpperCase)
.orElse(null);