2017-06-07 101 views
-6


在我的應用我想從陣列 如第一和重複元素列表的最後重複元素,的Java獲得第一和

String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one" 
       , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two" 
       , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three" 
       , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four" 
       , "five", "five", "five", "five", "five", "five" 
       , "six", "six", "six", "six", "six", "six", "six", "six", "six" 
       , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven" 
       , "eight", "eight", "eight", "eight", "eight", "eight" 
       , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine" 
       , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"}; 

對以上列舉我想輸出像

一個
一個

+0

將所有值映射到一個LinkedHashMap,然後將這些值重新添加到列表中,這次只添加一次發生的第一個和最後一個重複項。 – Sikorski

+2

請告訴我們你到目前爲止所嘗試過的。我們不會爲你做(家庭)工作。 – GhostCat

+0

如果您只對元素而不是第一個/最後一個元素的索引感興趣,那麼基本上只需要打印每個獨特元素兩次,換句話說就沒有任何意義。你到底在做什麼? – eldo

回答

0

你可以試試這個

public static void main(String[] args) { 

    String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one" 
      , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two" 
      , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three" 
      , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four" 
      , "five", "five", "five", "five", "five", "five" 
      , "six", "six", "six", "six", "six", "six", "six", "six", "six" 
      , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven" 
      , "eight", "eight", "eight", "eight", "eight", "eight" 
      , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine" 
      , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"}; 

    Map<String,Integer> itemMap=new LinkedHashMap<>(); 
    for (String item:strings){ 
     if(!itemMap.containsKey(item)){ 
      itemMap.put(item,1); 
     }else{ 
      itemMap.put(item, itemMap.get(item)+1); 
     } 
    } 

    for(Map.Entry<String, Integer> mapEntry:itemMap.entrySet()){ 
     if(mapEntry.getValue()>1){ 
      System.out.println(mapEntry.getKey()+"\n"+mapEntry.getKey()); 
     } 
    } 
} 
0

如果您正在使用Java8,您可以使用流API這樣的。

Stream.of(strings) 
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) 
      .entrySet() 
      .stream() 
      .filter(entry -> entry.getValue() > 1) 
      .forEach(entry -> System.out.println(entry.getKey() + "\n" + entry.getKey()));