java8 stream()流式写法 排序,去重

简单排序和去重:

初始化一个list:

List list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(5);
list.add(1);
list.add(0);
System.out.println(list);

排序:

List list1 = list.stream().sorted().collect(Collectors.toList());

反排序:

List list1 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

去重:

List integerList = list.stream().distinct().collect(Collectors.toList());

 

通过对象的属性排序和去重:

初始化一个对象的list:

List list = new ArrayList<>();
TestListToMap listToMap = new TestListToMap();
TestListToMap listToMap1 = new TestListToMap();
TestListToMap listToMap2 = new TestListToMap();
TestListToMap listToMap3 = new TestListToMap();
listToMap.setId(5);
listToMap.setName("第5");
listToMap1.setId(2);
listToMap1.setName("第2");
listToMap2.setId(5);
listToMap2.setName("第3");
listToMap3.setId(6);
listToMap3.setName("第6");
list.add(listToMap);
list.add(listToMap1);
list.add(listToMap2);
list.add(listToMap3);
System.out.println(list);

根据对象属性排序:

List orderList = list.stream()
        .sorted(Comparator.comparing(TestListToMap::getId))
        .collect(Collectors.toList());

根据对象属性去重最优雅的写法:

写一个自定义的方法:distinctByKey()

public  Predicate distinctByKey(Function keyExtractor) {
    Map seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

根据id去重:

List list1 = list.stream().filter(distinctByKey(l ->l.getId())).collect(Collectors.toList());

 

粘贴一个java8的stream()串行写法,parallelStream()并行写法和传统for写法的处理时间对比

@Test
public void contextLoads() {
    //初始化一个list
    long first = new Date().getTime();
    List list = new ArrayList<>();
    for (int i=1; i<5000; i++){
        TestListToMap listToMap = new TestListToMap();
        listToMap.setId(i);
        listToMap.setName("name"+i);
        listToMap.setAge(i+20);
        list.add(listToMap);
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println("传统所用时间" + (new Date().getTime() - first));


    long startTime = new Date().getTime();
    list.stream().forEach(f ->{
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println("串行所用时间" + (new Date().getTime() - startTime));


    long endTime = new Date().getTime();
    list.parallelStream().forEach(f ->{
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    System.out.println("并行所用时间" + (new Date().getTime() - endTime));


}

结果:

java8 stream()流式写法 排序,去重_第1张图片

 

你可能感兴趣的:(java8 stream()流式写法 排序,去重)