鉴于最近对List结构的数据类型处理的比较多,就查了一下相关的偷懒方式。
如下示例的目的是将Apple的一组拥有相同标志的对象赋予到Fruit对象里面。赋值的筛选条件为:两者的mark字段相同。
第一个实体类
public class Fruit {
private String id;
private String name;
private String type;
private String space;
private String mark;
@Transient
private List<Apple>appleList;//待会要赋值进去的对象
//。。。。其他语句偷个懒,节省空间
}
第二个实体类
public class Apple {
private String id;
private String name;
private String work;
private String prise;
private String mark;
参考示例:
import com.kernel.entity.Apple;
import com.kernel.entity.Fruit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
public class Lambda_java8_demo01 {
public static void main(String[] args) {
List<Fruit> fruits = new ArrayList<>();
List<Apple> apples = new ArrayList<>();
//初始化两组对象
for (int i = 0; i < 10; i++) {
Fruit fruit = new Fruit();
fruit.setId(UUID.randomUUID().toString());
fruit.setMark("aa" + i);
for (int j = 0; j < 3; j++) {
Apple apple = new Apple();
apple.setId(UUID.randomUUID().toString());
int m = i + 1;
apple.setMark("aa" + m);
apples.add(apple);
}
fruits.add(fruit);
}
//------------------------------------------------------------------------------------
//第一种赋值操作,将apple中符合条件(mark相等)的对象放入fruits中
// for (Fruit f:fruits){
// List<Apple>appleList=apples.stream()
// .filter(apple -> apple.getMark().equals(f.getMark()))
// .collect(Collectors.toList());
// f.setAppleList(appleList);
// }
System.out.println("条目1---:" + fruits.get(0).getAppleList());
//第二种赋值操作,将apple中符合条件(mark相等)的对象放入fruits中
fruits.forEach(fruit -> fruit.setAppleList(
apples.stream()
.filter(apple -> apple.getMark().equals(fruit.getMark()))
.collect(Collectors.toList())
));
System.out.println("条目2---:" + fruits.get(0).getAppleList().size());
//--------------------------------------------------------------------------
/*
获取中一组对象的某个属性列,比如获取“apples”中的id组成新的List。
*/
List<String> appleIdList = apples.stream()
.filter(apple -> apple.getId() != null)//筛选满足条件的对象,
// .map(apple -> apple.getId()) //定义反馈的元数据,可以用下面一种方法,
.map(Apple::getId) //定义反馈的元数据,简洁版
// .map(apple -> apple.getId()+"对ID进行拼接")//定义并操作反馈的元数据的
.distinct() //对获取到的一组数据去重
.collect(Collectors.toList()); //重新封装为list
System.out.println(appleIdList.size());
//------------------------------------------------------------------------------------
/*
条件判断相关,比如“apples”中是否含有某个apple对象的“mark”属性的值为“aa2”
anyMatch:部分满足条件
allMatch:全部满足条件
*/
boolean flag = apples.stream().anyMatch(apple -> "aa2".equals(apple.getMark()));
System.out.println("我猜含有aa2 这个mark的属性值:\t" + flag);
//执行结果:我猜含有aa2 这个mark的属性值: true
}
}