2013-03-07 120 views
0

我挣扎于解决使用Java排序由

下面这个问题是所需的输入和输出:采用ComparablecompareTo

Input 
1,9 
1,12 
1,7 
3,3 
2,4 
3,2 
2,2 
output 
1 -> 7,9,12 
2 -> 2,4 
3 -> 2,3 

我只可以实现与打印输出这样

1,7, 
1,9, 
1,12, 
2,2, 
2,4, 
3,2, 
3,3 

但这不是我想要的答案。有人可以帮我或给我任何建议吗? 这是我实现的代码,但这不是我想要的。

+3

你可以使用地图'整数,列表'类型的。 – 2013-03-07 14:37:37

+4

使用'TreeMap >',你只需要添加元素,然后打印两者的内容。 – 2013-03-07 14:38:34

回答

0

你可以使用这样的事情:

Map<Integer, Set<Integer>> result = new TreeMap<Integer, Set<Integer>>(); 

public void parseInput(int key, int value) { 
    if(result.get(key) == null) { // if you have not encountered the first integer yet, add it to your map. 
     result.put(key, new TreeSet<Integer>() {{ add(value); }}); 
    } else { // otherwise, just add your value to your existing set. The set will take care of duplicates. 
     result.get(key).add(value); 
    } 
} 
0

使用地图:

Map<Integer, List<Integer>> groups = new TreeMap<Integer, List<Integer>>(); 

对于每个输入线路,将它逗号和分开的数字:

String[] parts = inputLine.split(','); 
int group = Integer.parseInt(parts[0]); 
int member = Integer.parseInt(parts[1]); 

其中“基团”是逗号,“部件”前的数是之后的数字。 查找该组的映射项,创建如果它不存在:

List<Integer> list = groups.get(group); 
if (list==null) { 
    list = new ArrayList<Integer>(); 
    groups.put(group, list); 
} 

添加“成员”数到组:

group.add(member); 

输出留作练习:)

+0

我想他也希望子列表排序。 – 2013-03-07 14:52:29

+0

好点。在输出阶段,您可以在迭代之前使用列表上的Collections.sort()。 – NickJ 2013-03-07 14:55:05

+0

感觉很理解,但我不知道如何把你的代码放入我的。抱歉。你能修改我的代码吗? PLZ。 – user2144633 2013-03-07 15:11:12

0

假设你的字符串来在String[]这样的事情应该工作:

public static void main(String[] args) { 
    final Scanner sc = new Scanner(System.in); 
    final List<String> list = new ArrayList<String>(); 
    while (sc.hasNext()) { 
     final String next = sc.next(); 
     if ("print".equals(next)) { 
      break; 
     } 
     list.add(next); 
    } 
    printGrouped(list); 
} 

public static void printGrouped(Collection<String> args) { 
    final TreeMap<Integer, Set<Integer>> map = new TreeMap<Integer, Set<Integer>>() { 
     @Override 
     public Set<Integer> get(Object key) { 
      Set<Integer> list = super.get(key); 
      if (list == null) { 
       list = new TreeSet<Integer>(); 
       put((Integer) key, list); 
      } 
      return list; 
     } 
    }; 
    for (final String string : args) { 
     final String[] split = string.split(","); 
     final Set<Integer> list = map.get(Integer.parseInt(split[0])); 
     list.add(Integer.parseInt(split[1])); 
    } 
    for (final Entry<Integer, Set<Integer>> entry : map.entrySet()) { 
     final String valueString = entry.getValue().toString(); 
     System.out.println(entry.getKey() + " -> " + valueString.substring(1, valueString.length() - 1)); 
    } 
} 

输入:

1,9 
1,12 
1,7 
3,3 
2,4 
3,2 
2,2 
print 

输出:

1 -> 7, 9, 12 
2 -> 2, 4 
3 -> 2, 3 
+0

感谢bmoriss,但没有主要方法,仍然不知道如何将字符串数组添加到上面的代码中。对不起,我是初学者。请使其完成,以便我可以在eclipse中运行。 – user2144633 2013-03-07 16:53:23

+0

就像馅饼一样!或者至少像Java一样。 – 2013-03-07 17:13:06

+0

非常感谢。 – user2144633 2013-03-07 18:40:26