Java8 Stream常用操作
作者:互联网
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@AllArgsConstructor
@Builder
public class Fruit {
private Integer id;
private String name;
private Double money;
private Integer num;
}
测试用例
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
public class FruitTest {
List<Fruit> fruitList = null;
@Before
public void setup() {
fruitList = new ArrayList<>();
fruitList.add(new Fruit(1, "Apple1", 4.5, 11));
fruitList.add(new Fruit(1, "Apple2", 3.1, 2));
fruitList.add(new Fruit(2, "Banana", 4.89, 8));
fruitList.add(new Fruit(3, "Pear", 10.99, 9));
}
@Test
public void testGroupBy() {
System.out.println("testGroupBy()");
Map<Integer, List<Fruit>> map = fruitList.stream()
.collect(Collectors.groupingBy(Fruit::getId));
System.out.println(map);
}
@Test
public void testListToMap() {
System.out.println("testListToMap()");
Map<Integer, Fruit> map = fruitList.stream()
.collect(Collectors.toMap(Fruit::getId, a -> a, (k1, k2) -> k1));
System.out.println(map);
}
@Test
public void testFilter() {
System.out.println("testFilter()");
List<Fruit> ls = fruitList.stream()
.filter(a -> a.getName().equals("香蕉"))
.collect(Collectors.toList());
System.out.println(ls);
}
@Test
public void testMaxMin() {
System.out.println("testSum()");
Optional<Fruit> max = fruitList.stream().max(Comparator.comparingDouble(Fruit::getMoney));
max.ifPresent(System.out::println);
Optional<Fruit> min = fruitList.stream().min(Comparator.comparingDouble(Fruit::getMoney));
min.ifPresent(System.out::println);
}
标签:常用,Stream,System,public,fruitList,println,Fruit,Java8,out 来源: https://blog.csdn.net/qq_21009627/article/details/113799179