program story

Java에서 Map을 List로 변환하는 방법은 무엇입니까?

inputbox 2020. 10. 2. 22:13
반응형

Java에서 Map을 List로 변환하는 방법은 무엇입니까?


a Map<key,value>를 a 로 변환하는 가장 좋은 방법은 무엇입니까 List<value>? 모든 값을 반복하고 목록에 삽입하거나 뭔가를 간과하고 있습니까?


List<Value> list = new ArrayList<Value>(map.values());

가정 :

Map<Key,Value> map;

여기서 문제 Map는 두 개의 값 (키와 값)이있는 반면, List하나에는 하나의 값 (요소) 만 있다는 것입니다.

따라서 할 수있는 최선 List의 방법은 키 또는 값 중 하나를 가져 오는 것 입니다. (키 / 값 쌍을 유지할 래퍼를 만들지 않는 한).

다음이 있다고 가정합니다 Map.

Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");

로 키 메서드 에서 반환 된 에서 List새로 생성하여 얻을 수 있습니다 .ArrayListSetMap.keySet

List<String> list = new ArrayList<String>(m.keySet());

로 값을 List얻을 수 있지만 메서드 ArrayListCollection반환 한 에서 값을 만들 수 있습니다 Map.values.

List<String> list = new ArrayList<String>(m.values());

List를 얻은 결과 :

사과
다른
여보세요

Listof 값 을 얻은 결과 :

3.14
요소
세계

Java 8 Streams API 사용.

List<Value> values = map.values().stream().collect(Collectors.toList());

map.entrySet()Map.Entry키와 값을 모두 포함하는 개체 모음을 제공합니다 . 그런 다음 이것을 다음과 같이 원하는 컬렉션 개체로 변환 할 수 있습니다 new ArrayList(map.entrySet()).


무엇의 목록?

map귀하의 인스턴스 라고 가정 합니다.Map

  • map.values()Collection지도의 모든 값을 포함 하는를 반환 합니다.
  • map.keySet()Set지도의 모든 키를 포함 하는를 반환 합니다.

난 당신이에 포함 된 값을 변환 할 생각 MapA를을 list? 가장 쉬운 values()방법은 Map인터페이스 메서드 를 호출하는 것입니다 . Collection포함 된 값 개체의을 반환 합니다 Map.

이것은 개체에 Collection의해 뒷받침되며 Map개체에 대한 모든 변경 사항이 Map여기에 반영됩니다. 따라서 Map개체에 바인딩되지 않은 별도의 복사본을 원하면 아래와 같이 전달하는 List것과 같이 개체 를 만들기 만하면 됩니다.ArrayListCollection

ArrayList<String> list = new ArrayList<String>(map.values());

이렇게 할 수 있습니다

List<Value> list = new ArrayList<Value>(map.values());

결과의 값 List<Value>이 입력의 키 순서에 있는지 확인하려면 어떻게 든 Map<Key, Value>"통과"해야합니다 SortedMap.

어느 시작 콘크리트 용으로 SortedMap(예 : 구현 TreeMap) 또는 입력을 삽입 MapSortedMap해당 변환하기 전에 List. 예 :

Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));

Otherwise you'll get whatever native ordering the Map implementation provides, which can often be something other than the natural key ordering (Try Hashtable or ConcurrentHashMap, for variety).


    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);

    Set <Entry<String, Integer>> set = map.entrySet();

    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);

we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.


// you can use this
List<Value> list = new ArrayList<Value>(map.values());

// or you may use 
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());    
}

"Map<String , String > map = new HapshMap<String , String>;
 map.add("one","java");
 map.add("two" ,"spring");
 Set<Entry<String,String>> set =  map.entrySet();
 List<Entry<String , String>> list = new ArrayList<Entry<String , String>>    (set);
 for(Entry<String , String> entry : list ) {
   System.out.println(entry.getKey());
   System.out.println(entry.getValue());
 } "

Here's the generic method to get values from map.

public static <T> List<T> ValueListFromMap(HashMap<String, T> map) {
    List<T> thingList = new ArrayList<>();

    for (Map.Entry<String, T> entry : map.entrySet()) {
        thingList.add(entry.getValue());
    }

    return thingList;
}

HashMap<Integer, List<String>> map = new HashMap<>(); 
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("Primefaces");
list.add("JSF");
map.put(1,list);
if(map != null){
    return new ArrayList<String>((Collection<? extends String>) map.values());
}

참고URL : https://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java

반응형