2016-07-26 34 views
-1

嗨,我有大小列出三个说Iteraiting列表和搜索数

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

现在我还有一个列表,它的类型是长今

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次,等于希望103和104的大小重复三次我想要103和104只有如何做到这一点?

+0

而你是什么意思 “我想103和104”?你想在列表中返回它们?你想打印它们?如果你尝试重新格式化你的问题,这也会很好;) – Mark

+0

我想返回一个列表 – prasad

+0

请分享你现在的代码.. – Sanghita

回答

0

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

2.Traverse清单,并检查前一个元素的频率,如果当前元素不等于以前。

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

0

您可以使用:Collections.frequency

List<Long> newList = new ArrayList<>(); 
for(Long item : l) 
    if(Collections.frequency(l, item) == s.size()) 
     newList.add(item); 
return newList; 
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 
0

使用Collections Util frequency Method找到集合列表内的重复值。

请在下面找到工作代码。

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]