数组A=["G","D","B","H"] , 元素个数不定, 元素内容可以是任意字符
集合B=[{"id":"a",item:""},{"id":"a=b",item:""}], 数量不定, 结构固定
现在要把A中的元素均分给B中的item,分到多个时用逗号分隔.
对于A的元素个数小于或大于B的长度时, 只要求A要全部在B里出现就行了, 集合B的item至少要分到一个元素, 最好均分, 但集合B里的每个item不能有重复元素
有什么方法比较简便?
已经解决了
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by YSTYLE on 2017-04-17 0017. */ public class TEst { private static List<String> list = Lists.newArrayList(); private static List<Map> los = Lists.newArrayList(); public static void main(String[] args) { init(); List<String> augmented = list; int groupCount = los.size(); if (list.size() < groupCount){ augmented = Augmented(list, groupCount); } List<List<String>> chunk = chunk2(augmented, groupCount); for (int i = 0; i < los.size(); i++) { los.get(i).put("item", StringUtils.join(chunk.get(i),",") ); } System.out.println(los); } // 初始化测试数据 private static void init (){ int losCount = RandomUtils.nextInt(1,10); int listCount = RandomUtils.nextInt(1,10); for (int i = 0; i < listCount ; i++) { list.add(RandomStringUtils.randomAlphabetic(4)); } for (int i = 0; i < losCount; i++) { Map<String,Integer> map = new HashMap<String, Integer>(); map.put("id",RandomUtils.nextInt(10000,99999)); los.add(map); } System.out.println("生成的数组: " + list+" 数量: "+listCount); System.out.println("生成的对象数量: " + los.size()); } // 分组数据 public static <T> List<List<T>> chunk2(List<T> list, int group){ if (CollectionUtils.isEmpty(list)){ return Lists.newArrayList(); } List<List<T>> result = Lists.newArrayList(); Map<Integer,Set<T>> temp = Maps.newHashMap(); for (int i = 0; i < list.size(); i++) { if (temp.containsKey(i%group)) { Set<T> ts = temp.get(i % group); ts.add(list.get(i)); temp.put(i%group,ts); }else { Set<T> ts = Sets.newHashSet(); ts.add(list.get(i)); temp.put(i % group,ts); } } for (Set<T> ts : temp.values()) { result.add(Lists.newArrayList(ts)); } return result; } // 填充数据 public static <T> List<T> Augmented(List<T> list ,int size){ int length = CollectionUtils.isEmpty(list)?0:list.size(); if (length<1){ return Lists.newArrayList(); } List<T> result = Lists.newArrayList(list); if (length > size){ return result; } int count = size - length; for (int i = 0; i < count; i++) { result.add(list.get(RandomUtils.nextInt(0, length))); } return result; } }
雷雷
已经解决了
雷雷