java8的新特性之List集合双层for循环效率优化

首先先来一个案例简单模拟一下:

List wifes = new ArrayList();
List husbands= new ArrayList();
for(int i=0;i<8000;i++){
      wifes.add(new Wife(i, i+"的妻子", "000"+i));
}
for(int i=0;i<8000;i++){
      husbands.add(new Husband(i, "我是"+i, "000"+i));
}

//现在需要让妻子和丈夫进行配对组成一个家庭,按照familyId进行配对
在1.8之前你会这么写:
for(int i=0;i

如果按照jdk1.8的lamada表达式进行匹配的话。这个测试结果是ms级别的

// 将list转为Map,这里key一定要为唯一值,map(familyId,wife对象)
Map wifeMap = wife.stream().collect(
        Collectors.toMap(w -> w.getFamilyId(),
                w -> w));
// 匹配家庭
families = husband.stream().map(h -> {
    //从wifeMap里面根据husband的familyId去匹配。匹配上后组装成家庭对象然后放入集合。最后生成新的家庭集合
    return toFamily(wifeMap.get(h.getFamilyId()), h);
}).collect(Collectors.toList());

这是个测试案例:亲测如下:

package com.nuanshui.frms.report.manage;


import com.google.common.collect.Lists;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Author:
 * Date: 2016/11/23.
 * Time: 18:17
 */
public class TestFamily {
    @Test
    public void familyTest() {
        List wife = Lists.newArrayList();
        List husband = Lists.newArrayList();
        for(int i=0;i<8000;i++){
            wife.add(new Wife(i, i+"的妻子", "000"+i));
        }

        for(int i=0;i<8000;i++){
            husband.add(new Husband(i, "我是"+i, "000"+i));
        }
        Long startTime =System.currentTimeMillis();
        System.out.println("当前时间:"+startTime);
        List families = Lists.newArrayList();
        // 将list转为Map,这里key一定要为唯一值
        Map wifeMap = wife.stream().collect(
                Collectors.toMap(w -> w.getFamilyId(),
                        w -> w));
        // 匹配家庭
        families = husband.stream().map(h -> {
            return toFamily(wifeMap.get(h.getFamilyId()), h);
        }).collect(Collectors.toList());
        /*for(int i=0;i {
            System.out.println("家庭ID:" + family.getFamilyId() + ",丈夫:" + family.getHusbandName() + ",妻子:" + family.getWifeName());
        });
        Long endTime =System.currentTimeMillis();
        System.out.println("结束时间:"+endTime);
        System.out.println("------------耗时:---------"+(endTime-startTime)+"ms");
    }

    private Family toFamily(Wife wife, Husband husband) {
        Family family = new Family();
        family.setFamilyId(wife.getFamilyId());
        family.setHusbandName(husband.getHusbandName());
        family.setWifeName(wife.getWifeName());
        return family;
    }

    @Test
    public void test1(){
        //String.valueOf()
        BigDecimal c = new BigDecimal(651000);
        BigDecimal d = new BigDecimal(312);
        BigDecimal num3 = c.divide(d,10,BigDecimal.ROUND_HALF_DOWN);
        System.out.println(num3);
        BigDecimal b = (new BigDecimal(651000).divide(new BigDecimal(312)).setScale(1, BigDecimal.ROUND_HALF_UP));
        System.out.println(b);

    }
}

结果只要252ms;

这种效率天差地别。

 

你可能感兴趣的:(java)