找到重复的键时,映射值不会增加。请指教

时间:2018-09-17 02:47:42

标签: hashmap

我是Java新手。请帮助我获取以下代码的必需输出。 重复月份值时必须计算地图值

由于在不同线程上执行的2个子列表而发生问题。请告知是否需要在此代码中进行任何修改才能纠正要计数的地图值。

int size = inputList.size();
int listSize = size/numberOfThreads;
List<String> tmplist1 = inputList.subList(0, listSize);
int count = listSize;
for (int i=0;i<numberOfThreads;i++)
{

        if(listSize <= size) {
            t1 = new TotalOrderThread();    
         t1.setInput(tmplist1);
        Thread thread = new Thread(t1);
         thread.start();
         thread.join();
        if(listSize < size)
        tmplist1 = inputList.subList(listSize, listSize+count);
        listSize=listSize+count;
        }

*

Input:
123,03/04/2005
234,04/05/2005
567,03/04/2005
789,01/01/2005

输出:(第4个月重复两次,但该值未计为2)。请帮助找出错误。另外,是否有在迭代地图时将月份值打印为“ MMM”格式?

4    1
5    1
1    1
4    1

*

Map<Integer,Integer> orderMap = new HashMap<>();
for(int i=0;i<this.input.size();i++)
{
String details  = input.get(i);
String[] detailsarr = details.split(",");
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate id = LocalDate.parse(detailsarr[1], f);
int month = id.getMonthValue();
if(orderMap.containsKey(month))
{
int count = orderMap.get(month);
orderMap.put(month, count+1);
}

else
{
orderMap.put(month, 1);

 }
 }
for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
{
int month3 = entry.getKey();
int value = entry.getValue();
System.out.println(month3+ "    " +value);
}
}

1 个答案:

答案 0 :(得分:0)

我尝试了如下的代码。这个作品。

Map<Integer,Integer> orderMap = new HashMap<>();

String[] input  = {"123,03/04/2005", "234,04/05/2005", "567,03/04/2005", "789,01/01/2005"};

for(int i=0;i<input.length;i++)
{
    String details  = input[i];

    String[] detailsarr = details.split(",");
    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
    LocalDate id = LocalDate.parse(detailsarr[1], f);
    int month = id.getMonthValue();

    if(orderMap.containsKey(month))
    {
        int count = orderMap.get(month);
        orderMap.put(month, count+1);
    }

    else
    {
        orderMap.put(month, 1);

    }
 }

 for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
 {
    int month3 = entry.getKey();
    int value = entry.getValue();
    System.out.println(month3+ "    " +value);
 }