陣列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; } }
雷雷
已經解決了
雷雷