我在不同的A,B和C组中有1-10。 例如。 A-1,A-2,A-3,B-4,C-5,B-6,A-7,C-8,A-9,A,10
我想分别将小组分为A,B和C
A
1-3,
7,
9-10
B
4,
6
C
5,
8
任何人都可以用逻辑来帮助我吗?
答案 0 :(得分:0)
这是让你入门的东西:
String[] items = new String[] {
"A-1", "B-2", "A-5"
}
// This is the data structure that will receive the final data. The map key is the
// group name (e.g. "A" for item "A-15") and the map value is a list of numbers that
// have been found for that group. TreeMap is chosen because the groups will be sorted
// alphabetically. If you don't need that, you could also use HashMap.
Map<String, List<Integer>> groups = new TreeMap<String, List<Integer>>();
for (String item : items) {
// Split the item into the group and the number
String group = item.substring(0, 1);
String number = Integer.toString(item.substring(2));
// See if this group is already registered in our Map
List<Integer> groupData = groups.get(group);
if (groupData==null) {
groupData = new List<Integer>();
groups.put(group, groupData);
}
// Add the number to the data
groupData.add(number);
}
我在此假设您的商品始终采用 1个字母短划线的形式。如果它比这复杂一点,你需要看一下正则表达式(参见java class Pattern)。这个没有经过测试,我让你测试它并处理特殊情况。
此功能将输出{ "A-1", "A-2", "A-3", "B-2", "A-5" }
:
A -> {1, 2, 3, 5}
B -> {2}
如果你想合并连续的数字,你需要处理结果数字列表,但是如果你考虑一下,这不应该太难。
答案 1 :(得分:0)
Guava将帮助您创建所需的数据结构:
public static void main(final String[] args) {
String input = "A-1,A-2,A-3,B-4,C-5,B-6,A-7,C-8,A-9,A-10";
// create multimap
Map<String, Collection<Integer>> map=Maps.newTreeMap();
SortedSetMultimap<String, Integer> multimap = Multimaps.newSortedSetMultimap(
map, new Supplier<SortedSet<Integer>>() {
public SortedSet<Integer> get() {
return new TreeSet<Integer>();
}
});
//add data
Splitter entrySplitter = Splitter.on(',');
Splitter keyValueSplitter = Splitter.on('=');
for (String entry : entrySplitter.split(input)) {
Iterator<String> tokens = keyValueSplitter.split(entry).iterator();
multimap.put(tokens.next(), Integer.valueOf(tokens.next()));
}
// read data
for (Entry<String, Collection<Integer>> entry : map.entrySet()) {
System.out.println(entry.getKey()+":");
printMergedValues(entry.getValue());
}
}
private static void printMergedValues(Collection<Integer> value) {
// TODO implement this yourself
}
我唯一留给你的是加入小组
答案 2 :(得分:0)
我会这样:
String[] input = {"A-1","A-2","A-3","B-4","C-5","B-6","A-7","C-8","A-9"};
Map<String, Set<Integer>> result = new HashMap<String, Set<Integer>>();
String[] inputSplit;
String group;
Integer groupNumber;
for (String item : input)
{
inputSplit = item.split("-");
group = inputSplit[0];
groupNumber = Integer.valueOf( inputSplit[1] );
if ( result.get(group) == null ) { result.put(group, new HashSet<Integer>()); }
result.get(group).add(groupNumber);
}
for (Map.Entry entry : result.entrySet())
{
System.out.println( entry.getKey() + ":" + entry.getValue() );
}