Skip to content

Commit

Permalink
feat: Java 8 – Convert List to Map.
Browse files Browse the repository at this point in the history
  • Loading branch information
danielso2007 committed Dec 21, 2019
1 parent bada3c2 commit 5c0fba6
Show file tree
Hide file tree
Showing 4 changed files with 199 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package br.com.somejava8examples.commons.entities;

import java.util.Objects;

public class Hosting {

private int Id;
private String name;
private long websites;

public Hosting(int id, String name, long websites) {
Id = id;
this.name = name;
this.websites = websites;
}

public int getId() {
return Id;
}

public void setId(int id) {
Id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getWebsites() {
return websites;
}

public void setWebsites(long websites) {
this.websites = websites;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Hosting)) return false;
Hosting hosting = (Hosting) o;
return getId() == hosting.getId() &&
getWebsites() == hosting.getWebsites() &&
Objects.equals(getName(), hosting.getName());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getWebsites());
}

@Override
public String toString() {
return "Hosting{" +
"Id=" + Id +
", name='" + name + '\'' +
", websites=" + websites +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package br.com.somejava8examples.map;

import br.com.somejava8examples.commons.entities.Hosting;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ConvertListToMapService {

private List<Hosting> getList() {
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", 80000));
list.add(new Hosting(2, "linode.com", 90000));
list.add(new Hosting(3, "digitalocean.com", 120000));
list.add(new Hosting(4, "aws.amazon.com", 200000));
list.add(new Hosting(5, "google.com", 1));
return list;
}

public Map<Integer, String> listToMapCollectorsToMap() {
List<Hosting> list = getList();

// key = id, value - websites
Map<Integer, String> result1 = list.stream().collect(Collectors.toMap(Hosting::getId, Hosting::getName));

System.out.println("Result 1 : " + result1);

// key = name, value - websites
Map<String, Long> result2 = list.stream().collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites));

System.out.println("Result 2 : " + result2);

// Same with result1, just different syntax
// key = id, value = name
Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));

System.out.println("Result 3 : " + result3);

return result3;
}

public Map<String, Long> listToMapDuplicatedKeyDuplicated() {
List<Hosting> list = getList();

list.add(new Hosting(6, "linode.com", 100000)); // new line

// key = name, value - websites , but the key 'linode' is duplicated!?
Map<String, Long> result1 = list.stream().collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites));

System.out.println("Result 1 : " + result1);

return result1;
}

public Map<String, Long> listToMapDuplicatedKeyMerge() {
List<Hosting> list = getList();

list.add(new Hosting(6, "linode.com", 100000)); // new line

Map<String, Long> result1 = list.stream().collect(
Collectors.toMap(Hosting::getName, Hosting::getWebsites,
(oldValue, newValue) -> oldValue
)
);

System.out.println("Result 1 : " + result1);

return result1;
}

public Map listToMapSortCollect() {
List<Hosting> list = getList();
list.add(new Hosting(6, "linode.com", 100000));

//example 1
Map result1 = list.stream()
.sorted(Comparator.comparingLong(Hosting::getWebsites).reversed())
.collect(
Collectors.toMap(
Hosting::getName, Hosting::getWebsites, // key = name, value = websites
(oldValue, newValue) -> oldValue, // se a mesma chave, pegue a chave antiga
LinkedHashMap::new // returns a LinkedHashMap, keep order
));

System.out.println("Result 1 : " + result1);

return result1;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package br.com.somejava8examples.map;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@ActiveProfiles("test")
public class ConvertListToMapTest {

@Autowired
private ConvertListToMapService service;

@Test
public void listToMapCollectorsToMapTest() {
assertFalse(service.listToMapCollectorsToMap().isEmpty(), "List is empty");
}

@Test
public void listToMapDuplicatedKeyDuplicatedTest() {
Exception exception = assertThrows(IllegalStateException.class, () -> {service.listToMapDuplicatedKeyDuplicated();});

String expectedMessage = "Duplicate key linode.com (attempted merging values 90000 and 100000)";
String actualMessage = exception.getMessage();

assertEquals(actualMessage, expectedMessage);
}

@Test
public void listToMapDuplicatedKeyMergeTest() {
assertFalse(service.listToMapDuplicatedKeyMerge().isEmpty(), "List is empty");
}

@Test
public void listToMapSortCollectTest() {
assertFalse(service.listToMapSortCollect().isEmpty(), "List is empty");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@ public class StreamHasAlreadyBeenOperatedUponOrClosedTest {
private StreamHasAlreadyBeenOperatedUponOrClosedService service;

@Test
@DisplayName("Test Spring @Autowired Integration")
public void streamIsClosedTest() {
Exception exception = assertThrows(IllegalStateException.class, () -> {
service.streamIsClosed();
});
Exception exception = assertThrows(IllegalStateException.class, () -> {service.streamIsClosed();});

String expectedMessage = "stream has already been operated upon or closed";
String actualMessage = exception.getMessage();
Expand Down

0 comments on commit 5c0fba6

Please sign in to comment.