List<Apple> appleList = new ArrayList<>();//存放apple对象集合
|
1、在List<Apple>中,查找name为苹果1的对象Apple。
Optional<Apple> firstA = appleList .stream().filter(a -> "苹果1".equals(a.getName())).findFirst();
|
2、在List<Apple>中,查找name为苹果1的集合对象。
List<Apple> tmpList = appleList .stream().filter(a -> "苹果1".equals(a.getName())).collect(Collectors.toList());
|
3、在List<Apple>中,筛选出所有对象的name属性的集合对象。
List<
String> tmpList = appleList .stream().map(Apple::getName).collect(toList());
|
4、List<String>转换成带逗号的字符串
str =
"a, b, c"
commons-lang3-3.3.2.jar org.apache.commons.lang3.StringUtils.join(applyNameList, ",");
|
String str = "a, b, c";
List<String> result = Arrays.asList(StringUtils.split(str,","));
|
6、List转Map
id为key,apple对象为value
7、分组
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起
/**
* 需要注意的是:
|
//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
|
8、求和
将集合中的数据按照某个属性求和
BigDecimal:
//计算 总金额 BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add); System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48 Integer:
//计算 数量 int sum = appleList.stream().mapToInt(Apple::getNum).sum(); System.err.println("sum:"+sum); //sum:100 |
List<Apple> tmpList = appleList .stream().filter(a -> "苹果1".equals(a.getName())).collect(Collectors.toList());
|