Android map to list

Java 8 – Convert Map to List

By mkyong | Last updated: May 24, 2017

Viewed: 410,938 (+1,156 pv/w)

Few Java examples to convert a Map to a List

1. Map To List

For a simple Map to List conversion, just uses the below code :

Java 8 – Map To List

For Java 8, you can convert the Map into a stream, process it and returns it back as a List

3. Java 8 – Convert Map into 2 List

This example is a bit extreme, uses map.entrySet() to convert a Map into 2 List

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

In Java8 Map to List example, the below code snippet needs to change. Instead of map.keySet(), it should be map.values().

System.out.println(“n3. Export Map Value to List…, say no to banana”);
List result3 = map.keySet().stream()
.filter(x -> !”banana”.equalsIgnoreCase(x))
.collect(Collectors.toList());

public class Test <
public static void main(String[] args) <
TreeMap hm=new TreeMap();
hm.put(3, “arun singh”);
hm.put(5, “vinay singh”);
hm.put(1, “bandagi singh”);
hm.put(6, “vikram singh”);
hm.put(2, “panipat singh”);
hm.put(28, “jakarta singh”);

ArrayList al=new ArrayList(hm.values());
Collections.sort(al, new myComparator());

System.out.println(“//sort by values n”);
for(String obj: al) <
for(Map.Entry map2:hm.entrySet()) <
if(map2.getValue().equals(obj)) <
System.out.println(map2.getKey()+” “+map2.getValue());
>
>
>
>
>

class myComparator implements Comparator <
@Override
public int compare(Object o1, Object o2) <
String o3=(String) o1;
String o4 =(String) o2;
return o3.compareTo(o4);
>
>
OUTPUT=

3 arun singh
1 bandagi singh
28 jakarta singh
2 panipat singh
6 vikram singh
5 vinay singh

Источник

Conversion of Java Maps to List

A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed:

  • List of values and
  • List of keys from a Map.

Let us assume “map” is the instance of Map, henceforth as usual we all know it contains set and value pairs. so they are defined as follows:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

  • map.values() will return a Collection of the map’s values.
  • map.keySet() will return a set of the map’s keys.
Читайте также:  Сторонние темы для андроид

Methods:

  1. Passing sets of keys inside ArrayList constructor parameter
  2. Passing collection of map values generated by map.values() method to the ArrayList constructor parameter
  3. Using Streams API (only applicable after JDK 8 and onwards)

Let us discuss each of them

Methods 1: Passing sets of keys inside ArrayList constructor parameter

Procedure: We can convert Map keys to List of Keys bypassing set of map keys generated by map.keySet() method to the ArrayList constructor parameter as shown below

Syntax: Henceforth it as follows:

Method 2: List ListofKeys = new ArrayList(map.keySet());

We can convert Map keys to a List of Values by passing a collection of map values generated by map.values() method to ArrayList constructor parameter.

Syntax: Henceforth it is as follows:

Источник

Ответы на самые популярные вопросы об интерфейсе Map

0. Как перебрать все значения Map

1. Как конвертировать Map в List

2. Как отсортировать ключи мапы

Поместить Map.Entry в список и отсортировать его, используя Comparator.

В компараторе будем сравнивать исключительно ключи пар:

Если разобрался с лямбдами, эту запись можно существенно сократить:

Использовать SortedMap , а точнее, ее реализацию — TreeMap , которая в конструкторе принимает Comparator. Данный компаратор будет применяться к ключам мапы, поэтому ключами должны быть классы, реализующие интерфейс Comparable :

И, конечно, все можно переписать, используя лямбды:

В отличие от первого способа, используя SortedMap, мы всегда будем хранить данные в отсортированном виде.

3. Как отсортировать значения мапы

4. В чем разница между HashMap, TreeMap, и Hashtable

Порядок элементов. HashMap и Hashtable не гарантируют, что элементы будут храниться в порядке добавления. Кроме того, они не гарантируют, что порядок элементов не будет меняться со временем. В свою очередь, TreeMap гарантирует хранение элементов в порядке добавления или же в соответствии с заданным компаратором.

Допустимые значения. HashMap позволяет иметь ключ и значение null, HashTable — нет. TreeMap может использовать значения null только если это позволяет компаратор. Без использования компаратора (при хранении пар в порядке добавления) значение null не допускается.

Синхронизация. Только HashTable синхронизирована, остальные — нет. Если к мапе не будут обращаться разные потоки, рекомендуется использовать HashMap вместо HashTable.

И общее сравнение реализаций:

HashMap HashTable TreeMap
Упорядоченность элементов нет нет да
null в качестве значения да нет да/нет
Потокобезопасность нет да нет
Алгоритмическая сложность поиска элементов O(1) O(1) O(log n)
Структура данных под капотом хэш-таблица хэш-таблица красно-чёрное дерево

5. Как создать двунаправленную мапу

6. Как создать пустую Map

Обычная инициализация объекта:

Создание неизменяемой (immutable) пустой мапы:

Источник

Converting Java Maps to Lists

You’re probably no stranger to converting between data structures, so here are a number of ways you can do it using tools brought to us in Java 8.

Join the DZone community and get the full member experience.

Converting a Java Map to a List is a very common task. Map and List are common data structures used in Java. A Map is a collection of key value pairs. While a List is an ordered collection of objects in which duplicate values can be stored.

In this post, I will discuss different ways to convert a Map to a List.

For the example code in this post, I’ll provide JUnit tests. If you are new to JUnit, I suggest you go through my series on Unit Testing with JUnit.

Converting Map Keys to Lists

The Map class comes with the keyset() method that returns a Set view of the keys contained in the map. The code to convert all the keys of a Map to a Set is this.

Here is the JUnit test code.

The output on running the test in IntelliJ is this.

Читайте также:  Гпу ускорение андроид что это такое

Converting Map Values to Lists

You use the values() method of Map to convert all the values of Map entries into a List.

Here is the code to convert Map values to a List.

Here is the JUnit test code.

The output on running the test in IntelliJ is this.

Converting Maps to Lists Using Java 8 Streams

If you are into a more functional programming style, you can use streams (introduced in Java 8), along with some utility classes like Collectors, which provides several useful methods to convert a stream of Map entries to List.

The stream() method returns a stream of the keys from the Set of the map keys that Map.keySet() returns. The collect() method of the Stream class is called to collect the results in a List.

The Collectors.toList() passed to the collect() method is a generalized approach. You can collect elements of Stream in a specific collection, such as ArrayList, LinkedList, or any other List implementation. To do so, call the toColection() method, like this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.

Converting Map values to a List using streams is similar. You only need to get the stream of Map values that map.values() return, like this:

The test code is this:

The test output in IntelliJ is this.

Converting Generic Maps to Lists Using Streams and Java Lambdas

Until now, I’ve shown how to use method references with streams to perform conversions of Maps to Lists.

I personally prefer method references over lambda expressions because I find them to be clear and concise.

Also, when using collections, you will typically use generic collections and perform conversions between them.

For such collections, you can use streams with lambda expressions, like this.

The code to use a method reference is this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.

Published at DZone with permission of John Thompson , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Java 8: How to Convert a Map to List

Introduction

A Java Map implementation is an collection that maps keys to values. Every Map Entry contains key/value pairs, and every key is associated with exactly one value. The keys are unique, so no duplicates are possible.

A common implementation of the Map interface is a HashMap :

We’ve created a simple map of students (Strings) and their respective IDs:

A Java List implementation is a collection that sequentially stores references to elements. Each element has an index and is uniquely identified by it:

The key difference is: Maps have two dimensions, while Lists have one dimension.

Though, this doesn’t stop us from converting Maps to Lists through several approaches. In this tutorial, we’ll take a look at how to convert a Java Map to a Java List:

Convert Map to List of Map.Entry

Java 8 introduced us to the Stream API — which were meant as a step towards integrating Functional Programming into Java to make laborious, bulky tasks more readable and simple. Streams work wonderfully with collections, and can aid us in converting a Map to a List.

The easiest way to preserve the key-value mappings of a Map , while still converting it into a List would be to stream() the entries, which consist of the key-value pairs.

The entrySet() method returns a Set of Map.Entry elements, which can easily be converted into a List , given that they both implement Collection :

This results in:

Since Streams are not collections themselves — they just stream data from a Collection — Collectors are used to collect the result of a Stream ‘s operations back into a Collection . One of the Collectors we can use is Collectors.toList() , which collects elements into a List .

Читайте также:  Что лучше пионер или андроид

Convert Map to List using Two Lists

Since Maps are two-dimensional collections, while Lists are one-dimensional collections — the other approach would be to convert a Map to two List s, one of which will contain the Map’s keys, while the other would contain the Map’s values.

Thankfully, we can easily access the keys and values of a map through the keySet() and values() methods.

The keySet() method returns a Set of all the keys, which is to be expected, since keys have to be unique. Due to the flexibility of Java Collections — we can create a List from a Set simply by passing a Set into a List ‘s constructor.

The values() method returns a Collection of the values in the map, and naturally, since a List implements Collection , the conversion is as easy as passing it in the List ‘s constructor:

This results in:

Convert Map to List with Collectors.toList() and Stream.map()

We’ll steam() the keys and values of a Map , and then collect() them into a List :

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This results in:

This approach has the advantage of allowing us to perform various other operations or transformations on the data before collecting it. For example, knowing that we’re working with Strings — we could attach an anonymous function (Lambda Expression). For example, we could reverse the bytes of each Integer (key) and lowercase every String (value) before collecting them into a List :

Note: The map() method returns a new Stream in which the provided Lambda Expression is applied to each element. If you’d like to read more about the Stream.map() method, read our Java 8 — Stream.map() tutorial.

Running this code transforms each value in the streams before returning them as lists:

We can also use Collectors.toCollection() method, which allows us to chose the particular List implementation:

This results in:

Convert Map to List with Stream.filter() and Stream.sorted()

We’re not only limited to mapping values to their transformations with Stream s. We can also filter and sort collections, so that the lists we’re creating have certain picked elements. This is easily achieved through sorted() and filter() :

After we sorted the values we get the following result:

We can also pass in a custom comparator to the sorted() method:

Which results in:

If you’d like to read more about the sorted() method and how to use it — we’ve got a guide on How to Sort a List with Stream.sorted().

Convert Map to List with Stream.flatMap()

The flatMap() is yet another Stream method, used to flatten a two-dimensional stream of a collection into a one-dimensional stream of a collection. While Stream.map() provides us with an A->B mapping, the Stream.flatMap() method provides us with a A -> Stream mapping, which is then flattened into a single Stream again.

If we have a two-dimensional Stream or a Stream of a Stream, we can flatten it into a single one. This is conceptually very similar to what we’re trying to do — convert a 2D Collection into a 1D Collection. Let’s mix things up a bit by creating a Map where the keys are of type Integer while the values are of type List :

This results in:

Conclusion

In this tutorial, we have seen how to convert Map to List in Java in several ways with or without using Java 8 stream API.

Источник

Оцените статью