2015-05-05 13 views

Odpowiedz

26

Twój kod będzie musiał powtórzyć wszystkie elementy. Jeśli chcesz się upewnić, że nie ma duplikatów, prosta metoda, taka jak

public static <T> boolean containsUnique(List<T> list){ 
    Set<T> set = new HashSet<>(); 

    for (T t: list){ 
     if (!set.add(t)) 
      return false; 
    } 

    return true; 
} 
jest bardziej wydajna.

Ta metoda może być również zapisane jako (zakładając nierównoległe strumienie i środowiska gwintu Safe)

public static <T> boolean containsUnique(List<T> list){ 
    Set<T> set = new HashSet<>(); 
    return list.stream().allMatch(t -> set.add(t)); 
} 

lub @Holger wymienione w komentarzu

public static <T> boolean containsUnique(List<T> list){ 
    return list.stream().allMatch(new HashSet<>()::add); 
} 
+18

Może to być nawet jednolinijkowe: 'return list.stream(). AllMatch (nowy HashSet <>() :: dodaj);' – Holger

+2

@Holger Wow, nigdy o tym nie wiem. Codziennie uczę się czegoś nowego :) Dzięki! – Pshemo

+6

Wydaje się nieco niebezpieczne używać predykatu z efektami ubocznymi tutaj. –

1

kroki tej klasy jako StreamTool, ale myślę, że musi być jeszcze lepszy sposób z redukcją lub podobnym:

public class StreamTool { 

    /** 
    * Whether stream records are unique in that stream. 
    * @param <T> Type of records 
    * @param records 
    * @return true if there are no duplicates, false otherwise 
    */ 
    public static <T> boolean isUnique(Stream<T> records) { 
     return records.allMatch(new HashSet<>()::add); 
    } 
} 
7

Użyłem:
1. return list.size() == new HashSet<>(list).size();.

nie jestem pewien jak to porównać do:
2. return list.size() == list.stream().distinct().count();
i
3. return list.stream().sequential().allMatch(new HashSet<>()::add);
pod względem wydajności.

Ostatni (# 3) ma możliwość obsługi nie tylko kolekcji (np. List), ale także strumieni (bez ich jawnego zbierania).

0

Możesz użyć kolektora liczącego.

Stream.of(1, 3, 4, 6, 7, 5, 6) 
      .collect(Collectors.groupingBy(
        Function.identity(), Collectors.counting())) 
      .entrySet().stream().anyMatch(e -> e.getValue() > 1) 
Powiązane problemy