关注公众号:”奇叔码技术“
回复: “java面试题大全”或者“java面试题”
即可免费领取资料
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第6天,点击查看活动详情
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流试炼
@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().sorted() 排序
@Test
public void streamSorted(){
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);
//根据某个字段进行排序-升序,age
List<CollectionData.A> collect = aLists.stream().sorted(Comparator.comparing(CollectionData.A::getAge)).collect(Collectors.toList());
logger.info("{}",collect);
//[StreamTest.CollectionData.A(id=null, name=小明, age=1, sex=男),
// StreamTest.CollectionData.A(id=null, name=小明3, age=2, sex=男2),
// StreamTest.CollectionData.A(id=null, name=小明3, age=3, sex=男3),
// StreamTest.CollectionData.A(id=null, name=小明3, age=3, sex=男3)]
//如果是倒叙-最常用的,.reversed() 反转
List<CollectionData.A> collectReversed = aLists.stream().sorted(Comparator.comparing(CollectionData.A::getAge).reversed()).collect(Collectors.toList());
logger.info("{}",collectReversed);
//[StreamTest.CollectionData.A(id=null, name=小明3, age=3, sex=男3),
// StreamTest.CollectionData.A(id=null, name=小明3, age=3, sex=男3),
// StreamTest.CollectionData.A(id=null, name=小明3, age=2, sex=男2),
// StreamTest.CollectionData.A(id=null, name=小明, age=1, sex=男)]
//如果是单个字段,可以直接自然排序-升序
List<Long> collectNaturalOrder = aLists.stream().map(m -> m.getAge()).sorted(Comparator.naturalOrder()).collect(Collectors.toList());
logger.info("{}",collectNaturalOrder);
//[1, 2, 3, 3]
//如果是单个字段,可以直接反转-降序
List<Long> collectReverseOrder = aLists.stream().map(m -> m.getAge()).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
logger.info("{}",collectReverseOrder);
//[3, 3, 2, 1]
}
}