Programing

Java Set에서 * 모든 * 값을 얻는 좋은 방법은 무엇입니까?

lottogame 2020. 12. 31. 07:50
반응형

Java Set에서 * 모든 * 값을 얻는 좋은 방법은 무엇입니까?


간단한 감안할 때 Set<T>, 얻을 수있는 좋은 방법 (코드 빠르고 몇 줄) 무엇을 어떤 로부터 값은 Set?

를 사용하면 List쉽습니다.

List<T> things = ...;
return things.get(0);

그러나하는로 Set, 어떤이 없습니다 .get(...)때문에 방법 Set의 주문한되지 않습니다.


A Set<T>Iterable<T>이므로 첫 번째 요소에 대한 반복이 작동합니다.

Set<T> things = ...;
return things.iterator().next();

Guava에는 위의 스 니펫 이 더 좋을 수 있지만이를 수행 하는 방법있습니다.


스트림이 존재하기 때문에 그렇게 할 수도 있지만 클래스를 사용해야합니다 java.util.Optional. Optional요소에 대한 래퍼 클래스이거나 명시 적으로 요소가 없습니다 (Nullpointer를 피함).

//returns an Optional.
Optional <T> optT = set.stream().findAny();

//Optional.isPresent() yields false, if set was empty, avoiding NullpointerException
if(optT.isPresent()){
    //Optional.get() returns the actual element
    return optT.get();
}

얻기 모든 것이 하나의 예를 들어, 요구 계산할 때 매우 일반적이지만, - 임의 또는 취사 선택하지 않는 경우 - 셋트 또는 컬렉션에서 요소 것은 드문 수요처럼 보일 수 지도에서 키 또는 값 오브젝트에 대한 통계 및 분을 초기화해야한다 / 최대 값 . Set / Collection any 요소 (Map.keySet () 또는 Map.values ​​()에 의해 반환 됨)는 요소의 최소 / 최대 값을 업데이트하기 전에이 초기화에 사용됩니다 .

그렇다면이 문제에 직면했을 때 동시에 메모리와 실행 시간을 줄이고 코드를 명확하게 유지하려고 할 때 어떤 옵션이 있습니까?

흔히 " Set to ArrayList로 변환하고 첫 번째 요소를 가져옵니다 "라는 일반적인 결과를 얻습니다 . 큰! 수백만 개의 항목과 추가 처리주기의 또 다른 배열로 Set에서 개체 검색 하고 배열을 할당 하고 채 웁니다 .

HashMap<K,V> map;
List<K> list = new ArrayList<V>(map.keySet()); // min/max of keys
min = max = list.get(0).some_property(); // initialisation step
for(i=list.size();i-->1;){
 if( min > list.get(i).some_property() ){ ... }
 ...
}

또는 반복자와 함께 루프를 사용하여 최소 / 최대가 초기화되어야 함을 나타내는 플래그와 해당 플래그가 루프의 모든 반복에 대해 설정되었는지 확인하는 조건문을 사용할 수 있습니다. 이것은 많은 조건부 검사를 의미합니다.

boolean flag = true;
Iterator it = map.keySet().iterator();
while( it.hasNext() ){
  if( flag ){
    // initialisation step
    min = max = it.next().some_property();
    flag = false;
  } else {
    if( min > list.get(i).some_property() ){ min = list.get(i).some_property() }
  ...
  }
}

또는 루프 외부에서 초기화를 수행하십시오.

HashMap<K,V> map;
Iterator it = map.keySet().iterator();
K akey;
if( it.hasNext() ){
  // initialisation step:
  akey = it.next();
  min = max = akey.value();
  do {
    if( min > list.get(i).some_property() ){ min = akey.some_property() }
  } while( it.hasNext() && ((akey=it.next())!=null) );
}

그러나 최소 / 최대가 필요할 때마다 프로그래머를 대신하여 (그리고 JVM을 대신하여 반복기를 설정하는)이 모든 매뉴얼이 정말 가치가 있습니까?

The suggestion from a javally-correct ol' sport could well be: "wrap your Map in a class which keeps track of min and max values when put or deleted!".

There is another situation which in my experience the need for just any item from a Map arises. This is when the map contains objects which have a common property - all the same for all of them in that map - and you need to read that property. For example suppose there is a Map of holding bins of the same histogram which have the same number of dimensions. Given such a Map you may need to know the number of dimensions of just any Histobin in the Map in order to, say, create another Histobin of the same dimensions. Do I need to setup an iterator again and dispose it after calling next() just once? I will skip the javally-correct person's suggestion to this situation.

And if all the trouble in getting the any element causes insignificant memory and cpu cycles increase, then what about all the code one has to write just to get the hard-to-get any element.

We need the any element. Give it to us!

ReferenceURL : https://stackoverflow.com/questions/13692700/good-way-to-get-any-value-from-a-java-set

반응형