一套平均分配算法代码-JAVA

用的频繁,留个记录,下次无脑抄,保住自己稀疏的发量


    public static void main(String[] args) {
        List _users = Lists.newArrayList("A","B","C");
        List  ids = Lists.newArrayList("1","2","3","4","1","2","3","4");;
        int dyCount = ids.size() % _users.size(); //多出来的

        int pjCount = (ids.size() - dyCount) / _users.size();//平均的

        Map> cacheMap = Maps.newConcurrentMap();

        for (int i = 0; i < _users.size(); i++) {
            String userId = _users.get(i);
            List _ids = ids.subList(i * pjCount, i * pjCount + pjCount);
            cacheMap.put(userId, new CopyOnWriteArrayList<>(_ids));
        }

        if (_users.size() * pjCount < ids.size()) {
            List _ids = ids.subList(_users.size() * pjCount, ids.size());
            for (int i = 0; i < _ids.size(); i++) {
                String userId = _users.get(i % _users.size());
                List userOfIds = cacheMap.get(userId);
                userOfIds.add(_ids.get(i));
            }
        }
        System.out.println();


    }

你可能感兴趣的:(算法,java)