1.创建实体
public class Apple {
private Integer id
;
private String name
;
private BigDecimal money
;
private Integer num
;
public Integer
getId() {
return id
;
}
public void setId(Integer id
) {
this.id
= id
;
}
public String
getName() {
return name
;
}
public void setName(String name
) {
this.name
= name
;
}
public BigDecimal
getMoney() {
return money
;
}
public void setMoney(BigDecimal money
) {
this.money
= money
;
}
public Integer
getNum() {
return num
;
}
public void setNum(Integer num
) {
this.num
= num
;
}
@Override
public String
toString() {
return "Apple{" +
"id=" + id
+
", name='" + name
+ '\'' +
", money=" + money
+
", num=" + num
+
'}';
}
public Apple(){}
public Apple(Integer id
, String name
, BigDecimal money
, Integer num
) {
this.id
= id
;
this.name
= name
;
this.money
= money
;
this.num
= num
;
}
}
2.给List赋值
List
<Apple> appleList
= new ArrayList<>();
Apple apple11
= new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12
= new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple applel3
= new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple applel4
= new Apple(3,"荔枝",new BigDecimal("9.99"),40);
appleList
.add(apple11
);
appleList
.add(apple12
);
appleList
.add(applel3
);
appleList
.add(applel4
);
3.根据ID进行分组
Map
<Integer
, List
<Apple>> groupBy
= appleList
.stream().collect(Collectors
.groupingBy(Apple
::getId
));
System
.out
.println("groupBy:" + groupBy
);
4.List -> Map
Map
<Integer, Apple> appleMap
= appleList
.stream().collect(Collectors
.toMap(Apple
::getId
, a
-> a
,(k1
,k2
)->k1
));
5.Map的三种遍历方式
Set
<Integer> integers
= appleMap
.keySet();
for (Integer integer
: integers
) {
System
.out
.println("第一种->" + appleMap
.get(integer
));
}
Iterator
<Map
.Entry
<Integer, Apple>> iterator
= appleMap
.entrySet().iterator();
while (iterator
.hasNext()){
Map
.Entry
<Integer, Apple> next
= iterator
.next();
System
.out
.println("第二种->" + next
.getKey() + ":" + next
.getValue());
}
for (Map
.Entry
<Integer, Apple> integerAppleEntry
: appleMap
.entrySet()) {
System
.out
.println("第三种->" + integerAppleEntry
.getKey() + ":" + integerAppleEntry
.getValue());
}
6.Filter
List
<Apple> filterList
= appleList
.stream().filter(a
-> a
.getName().equals("香蕉")).collect(Collectors
.toList());
System
.out
.println("filterList:"+filterList
);
7.BigDecimal的统计
BigDecimal totalMoney
= appleList
.stream().map(Apple
::getMoney
).reduce(BigDecimal
.ZERO
, BigDecimal
::add
);
System
.out
.println("totalMoney:"+totalMoney
);
8.去重
List
<Apple> collect
= appleList
.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Apple
::getId
))), ArrayList
::new));
collect
.stream().forEach(ret
->{
System
.out
.println(ret
);
});
人若成就一道景致,则无关春夏秋冬。
转载请注明原文地址:https://tech.qufami.com/read-15422.html