关注公众号:”奇叔码技术“
回复: “java面试题大全”或者“java面试题”
即可免费领取资料
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情
package util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
//strem流试炼2
@SpringBootTest
public class StreamTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//一个接口中存放多个对象--一般用于一个entity实体类以外所有关的vo(值对象)、dto(数据传输对象)等对象都可以存放在一起(类少些了,也方便查询和删改)
public interface CollectionData{
@Data
@NoArgsConstructor
@AllArgsConstructor
public class A{
private Long id;
private String name;
private Long age;
private String sex;
public A(String name, Long age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ADTO{
private Long age;
private String sex;
}
}
//stream().distinct() 一般用于对象的完全去重
@Test
public void streamDistinct(){
ArrayList<CollectionData.A> aLists = new ArrayList<>();
CollectionData.A a1 = new CollectionData.A("小明", 1l, "男");
CollectionData.A a2 = new CollectionData.A("小明2", 2l, "男2");
CollectionData.A a3 = new CollectionData.A("小明3", 3l, "男3");
CollectionData.A a4 = new CollectionData.A("小明3", 3l, "男3");
aLists.add(a1);
aLists.add(a2);
aLists.add(a3);
aLists.add(a4);
//1、进行去重,只有两个完全一样的对象才会去重,这里去重了最后一个对象
List<CollectionData.A> collect = aLists.stream().distinct().collect(Collectors.toList());
//[StreamTest.CollectionData.A(id=null, name=小明, age=1, sex=男),
// StreamTest.CollectionData.A(id=null, name=小明2, age=2, sex=男2),
// StreamTest.CollectionData.A(id=null, name=小明3, age=3, sex=男3)]
logger.info("{}",collect);
}
//stream().distinct() 一般用于某个字段的去重
@Test
public void streamDistinctFields(){
ArrayList<CollectionData.A> aLists = new ArrayList<>();
CollectionData.A a1 = new CollectionData.A("小明", 1l, "男");
CollectionData.A a2 = new CollectionData.A("小明3", 2l, "男2");
CollectionData.A a3 = new CollectionData.A("小明3", 3l, "男3");
CollectionData.A a4 = new CollectionData.A("小明3", 3l, "男3");
aLists.add(a1);
aLists.add(a2);
aLists.add(a3);
aLists.add(a4);
//1、进行去重,比对,某个字段进行去重,一般用于sql查询之后的结果(或者sql进行group by分组),再做某个字段的去重
//这里进行去重,name相同的进行去重
ArrayList<CollectionData.A> collect = aLists.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(new Function<CollectionData.A, String>() {
@Override
public String apply(CollectionData.A a) {
return a.getName();
}
}))), ArrayList::new));
logger.info("{}",collect);
//[StreamTest.CollectionData.A(id=null, name=小明, age=1, sex=男),
// StreamTest.CollectionData.A(id=null, name=小明3, age=2, sex=男2)]
}
}