Iteraiting列表并搜索计数

时间:2016-07-26 08:59:31

标签: java

嗨,我有三个大小的名单

 List<Long> s  = new Arraylist<Long>();
        now s.size()=3;

现在我有另一个类型为long

的列表
List<Long> l = new ArrayList<Long>();

l.add(101l);
l.add(102l);
l.add(102l);
l.add(103l);
l.add(103l);
l.add(103l);
l.add(104l);
l.add(104l);
l.add(104l);

现在因为103重复3次并且等于s的大小我想103和104重复三次我想103和104只是如何做到???

4 个答案:

答案 0 :(得分:0)

1.您可以对列表进行排序

2.如果当前元素与前一元素不相等,则遍历列表并检查前一元素的频率。

3.如果频率等于所需列表的大小,请将其添加到另一个列表中。

答案 1 :(得分:0)

您可以使用:Collections.frequency

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

答案 2 :(得分:0)

试试这个。

 List<Long> l = new ArrayList<Long>();
 l.add(101l);
 l.add(102l);
 l.add(102l);
 l.add(103l);
 l.add(103l);
 l.add(103l);
 l.add(104l);
 l.add(104l);
 l.add(104l); 

  //use below code, on iterating valueCount map you will get each value number of occurance.

       Map<Long,Integer> valueCount=new HashMap<Long,Integer>;

       for(Long value:l){

       if(valueCount.contains(value))
       {
        int count=valueCount.get(value);
        i++;
        valueCount.put(value,count);
       }else
       {
        valueCount.put(value,1);
       }
      }

     // iterate map and get count of each value

答案 3 :(得分:0)

使用Collections Util frequency Method在Collection列表中找到重复的值。

请找到下面的工作代码。

    List<Long> nonDuplicateList = new ArrayList<Long>();

    nonDuplicateList.add(101L);
    nonDuplicateList.add(102L);
    nonDuplicateList.add(102L);
    nonDuplicateList.add(103L);
    nonDuplicateList.add(103L);
    nonDuplicateList.add(103L);
    nonDuplicateList.add(104L);
    nonDuplicateList.add(104L);
    nonDuplicateList.add(104L);

    System.out.println("Original list " + nonDuplicateList);

    List<Long> repeatedList = new ArrayList<Long>();
    for (Long longValue : nonDuplicateList) {
        if (Collections.frequency(nonDuplicateList, longValue) > 2) {
            if (!repeatedList.contains(longValue)) {
                repeatedList.add(longValue);
            }

        }
    }
    System.out.println("Duplicated List " + repeatedList);

输出

Original list[101, 102, 102, 103, 103, 103, 104, 104, 104]
Duplicated List [103, 104]