Mục lục bài viết

Kinh Nghiệm về Convert List to Map = list Java 8 Mới Nhất

Cập Nhật: 2022-03-15 10:00:10,Bạn Cần biết về Convert List to Map = list Java 8. Bạn trọn vẹn có thể lại phản hồi ở cuối bài để Mình đc lý giải rõ ràng hơn.

673

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring E-Mail,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

Tóm lược đại ý quan trọng trong bài

  • Convert Map to List of Map.Entry
  • Convert Map to List using Two Lists
  • Convert Map to List with Collectors.toList() and Stream.map()
  • Convert Map to List with Stream.filter() and Stream.sorted()
  • Convert Map to List with Stream.flatMap()

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:

Map students = new HashMap();
students.put(132, “James”);
students.put(256, “Amy”);
students.put(115, “Young”); System.out.println(“Print Map: “ + students);

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

Print Map: 256=Amy, 115=Young, 123=James

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

List list = new ArrayList(Arrays.asList(“James”, “Amy”, “Young”));
System.out.println(list);
System.out.println(String.format(“Third element: %s”, list.get(2));

[James, Amy, Young]
Third element: Young

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:

List<Map.Entry> singleList = students.entrySet() .stream() .collect(Collectors.toList()); System.out.println(“Single list: “ + singleList);

This results in:

Single list: [256=Amy, 115=Young, 132=James]

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 Lists, 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:

List keyList = new ArrayList(students.keySet());
List valueList = new ArrayList(students.values()); System.out.println(“Key List: “ + keyList);
System.out.println(“Value List: “ + valueList);

This results in:

Key List: [256, 115, 132]
Value List: [Amy, Young, James]

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:

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!

List keyList = students.keySet().stream().collect(Collectors.toList());
System.out.println(“Key list: “ + keyList); List valueList = students.values().stream().collect(Collectors.toList());
System.out.println(“Value list: “ + valueList);

This results in:

Key list: [256, 115, 132]
Value list: [Amy, Young, James]

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:

List keyList = students.keySet() .stream() .map(Integer::reverseBytes) .collect(Collectors.toList()); System.out.println(“Key list: “ + keyList); List valueList = students.values() .stream() .map(String::toLowerCase) .collect(Collectors.toList()); System.out.println(“Value list: “ + valueList);

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:

Key list: [65536, 1929379840, -2080374784]
Value list: [amy, young, james]

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

List keyList = students.keySet() .stream() .collect(Collectors.toCollection(ArrayList::new));
List valueList = students.values() .stream() .collect(Collectors.toCollection(ArrayList::new)); System.out.println(“Key list: “ + keyList);
System.out.println(“Value list: “ + valueList);

This results in:

Key list: [256, 115, 132]
Value list: [Amy, Young, James]

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

We’re not only limited to mapping values to their transformations with Streams. 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():

List sortedValueList = students.values() .stream() .sorted() .collect(Collectors.toList()); System.out.println(“Sorted Values: “ + sortedValueList);

After we sorted the values we get the following result:

Sorted Values: [Amy, James, Young]

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

List sortedValueList = students.values() .stream() .filter(value-> value.startsWith(“J”)) .collect(Collectors.toList()); System.out.println(“Sorted Values: “ + sortedValueList);

Which results in:

Sorted Values: [James]

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:

Map<Integer, List> newMap = new HashMap(); List firstName = new ArrayList();
firstName.add(0, “Jon”);
firstName.add(1, “Johnson”);
List secondName = new ArrayList();
secondName.add(0, “Peter”);
secondName.add(1, “Malone”); newMap.put(1, firstName);
newMap.put(2, secondName);

List valueList = newMap.values()
.stream()

.flatMap(e -> e.stream())
.collect(Collectors.toList());

System.out.println(valueList);

This results in:

[Jon, Johnson, Peter, Malone]

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.

Reply
6
0
Chia sẻ

đoạn Clip hướng dẫn Share Link Down Convert List to Map = list Java 8 ?

– Một số Keywords tìm kiếm nhiều : ” Video full hướng dẫn Convert List to Map = list Java 8 tiên tiến và phát triển nhất , Chia Sẻ Link Tải Convert List to Map = list Java 8 “.

Hỏi đáp vướng mắc về Convert List to Map = list Java 8

Bạn trọn vẹn có thể để lại Comment nếu gặp yếu tố chưa hiểu nha.
#Convert #List #Map #list #Java Convert List to Map = list Java 8