我有一组存储在HashMap中的元素。因此,我必须比较这些值,如果检索到的值大于某个值,则应将其分组为Group-n(其中n =表示第n组)。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class GroupTag{
public static void main(String[] args)
{
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("0-1", 33);
myMap.put("0-2", 29);
myMap.put("0-3", 14);
myMap.put("0-4", 8);
myMap.put("1-2", 41);
myMap.put("1-3", 15);
myMap.put("1-4", 17);
myMap.put("2-3", 1);
myMap.put("2-4", 16);
myMap.put("3-4", 18);
for(int i = 0; i < 5; i++)
{
for(int j = i+1; j < 4; j++)
{
String testLine = i+"-"+j;
int itemA = myMap.get(testLine);
boolean greaterThanAll = true;
for(int k = j+1; k < 5; k++)
{
String newLine = j+"-"+k;
int itemB = myMap.get(newLine);
if(itemA <= itemB)
{
//Condition: e.g IF and ONLY IF all myMap.get(0-1)>than myMap.get(1-2),
//myMap.get(1-3),myMap.get(1-n)
//THEN trigger an event to group ALL of myMap.get(1-n) to myMap.get(0-1)
//THEN remove all the values that satisfied the condition from the HashMap list
greaterThanAll = false;
break;
}
}
if (greaterThanAll)
{
for(int m = j+1; m < 5; m++)
{
String removeLine = j+"-"+m;
//Group myMap.get(removeLine) to myMap.get(testLine)
//myMap.remove(removeLine);
System.out.println("Index " + removeLine + " : " + myMap.get(removeLine));
}
//myMap.remove(testLine);
System.out.println("Main Index " + testLine + " : " + myMap.get(testLine));
}
}
}
}
}
Example of how the element are compared:
IF myMap.get("0-1")>myMap.get("1-n"): Grouped to Group 0 and REMOVE both values from list
IF myMap.get("0-2")>myMap.get("2-n"): Grouped to Group 1 and REMOVE both values from list
IF myMap.get("0-3")>myMap.get("3-n"): Grouped to Group 2 and REMOVE both values from list
THEN the loop goes on to compare myMap.get("1-2")>myMap.get("2-n") and so on..
Desired outcome:
Retrieve number of Groups: 2
Retrieve size of Group 0: 3
Retrieve elements in Group 1: [1, 16]
基本上,我只需要一种方法将一组元素或数据分组/存储在一起?
编辑:我发布了条件。我认为将条件排除会更容易,因为我只想将一些元素组合在一起。答案 0 :(得分:2)
首先,是否正在构建符合您要求的预期字符串键?迭代地图并查看值是否大于数字不是更容易吗?
也许LambdaJ正是您所寻找的(直到Java获得本机Lambda表达式)。
答案 1 :(得分:0)
参见: http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html#subSet(E,布尔值,E,布尔值)
您可以在TreeSet中使用subset()操作。
public NavigableSet<E> subSet(E fromElement,
boolean fromInclusive,
E toElement,
boolean toInclusive)
OR
public SortedSet<E> subSet(E fromElement,
E toElement)