You were almost correct with groupingBy, but the second parameter of that is a Collector, not a Function. Thus I used toMap.
Map<String, Integer> map = Stream.of("bla", "blabla", "blablabla").distinct()
.collect(Collectors.toMap(Function.identity(), String::length));
Answer from Eugene on Stack OverflowYou were almost correct with groupingBy, but the second parameter of that is a Collector, not a Function. Thus I used toMap.
Map<String, Integer> map = Stream.of("bla", "blabla", "blablabla").distinct()
.collect(Collectors.toMap(Function.identity(), String::length));
You don't have to do something so complicated. Here is an example code:
...
...
List<String> ll= // the list of words that you have.
Map<String,Integer> map = new HashMap<>();// or any other kind of map you want to create
for(String s:ll){
map.put(s,s.length());
}
Now you have a map that satisfies your requirement.
Lets track it down:
The way you have initiated:
List<Map<String, String>> myList = new ArrayList<Map<String, String>>();
So you have a list of maps.
Now how do we get an item from a List, there are two ways:
for(int index = 0 ; index < myList.size() ; index++){
Map<String, String> listItem = myList.get(index);
// Iterate over the map.
}
or
for(Map<String, String> listItem : myList){
// Iterate over the map.
}
Now how do we iterate over the map:
Iterator it = listItem.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
You need to get your map from the list before getting the values out of your map. Something like below :
Map<String, String> myMap ;
for (int j=0; j<myList.size(); j++)
{
myMap = mylist.get(i);
String val1 = myMap.get("value1");
String val2 = myMap.get("value2");
}
Map<String, List<String>> myMaps = new HashMap<String, List<String>>();
for (DataObject item : myList) {
if (!myMaps.containsKey(item.getKey())) {
myMaps.put(item.getKey(), new ArrayList<String>());
}
myMaps.get(item.getKey()).add(item.getValue());
}
I would use the guavas Multimap implementation. But it is easy doable with the standard JDK aswell.
Example standard JDK:
public static void main(String[] args) {
Scanner s = new Scanner(
"car toyota\n" +
"car bmw\n" +
"car honda\n" +
"fruit apple\n" +
"fruit banana\n" +
"computer acer\n" +
"computer asus\n" +
"computer ibm");
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
while (s.hasNext()) {
String key = s.next();
if (!map.containsKey(key))
map.put(key, new LinkedList<String>());
map.get(key).add(s.next());
}
System.out.println(map);
}
Example guava:
public static void main(String[] args) {
Scanner s = new Scanner(
"car toyota\n" +
"car bmw\n" +
"car honda\n" +
"fruit apple\n" +
"fruit banana\n" +
"computer acer\n" +
"computer asus\n" +
"computer ibm");
Multimap<String, String> map = LinkedListMultimap.create();
while (s.hasNext())
map.put(s.next(), s.next());
System.out.println(map);
}
Output (both implementations):
{car=[toyota, bmw, honda], fruit=[apple, banana], computer=[acer, asus, ibm]}
You can create a class Company and then subsequent operations become much simpler.
class Company {
String company;
String billType;
String billPeriod;
public Company(String company, String billType, String billPeriod) {
this.company = company;
this.billType = billType;
this.billPeriod = billPeriod;
}
// getters, setters, toString, etc
}
Initialize the list :
List<Company> list = new ArrayList<>();
list.add(new Company("LG", "A", "09-2018"));
list.add(new Company("LG", "A", "09-2018"));
list.add(new Company("LG", "A", "09-2018"));
list.add(new Company("LG", "B", "01-2019"));
list.add(new Company("LG", "B", "01-2019"));
list.add(new Company("Samsung", "A", "10-2018"));
list.add(new Company("Samsung", "A", "10-2018"));
list.add(new Company("Samsung", "B", "11-2018"));
Now for an example, you can group by company name :
Map<String, Long> map = list.stream().collect(
Collectors.groupingBy(Company::getCompany,
Collectors.mapping((Company c) -> c, Collectors.counting())));
Now it becomes much easier to perform other operations as you desire. Also, here instead of creating 8 maps you end up dealing with just 1 list.
It's really difficult to grouping and counting a map because your map data will be changed after you increase your counter value. Therefore, you must save the original data of the map, and save your counter value to the another map. Join 2 maps after your counting process is complete.
Map<Map<String, Object>, Long> counterData = listBeforeGroup.stream().collect(Collectors.groupingBy(m -> m, Collectors.counting()));
List<Map<String, Object>> listAfterGroup = new ArrayList<>();
for (Map<String, Object> m : counterData.keySet()) {
Map<String, Object> newMap = new HashMap<>(m);
newMap.put("count", counterData.get(m));
listAfterGroup.add(newMap);
}
Update Java 8 approach, not easy to debug
List<Map<String, Object>> listAfterGroup = listBeforeGroup.stream().collect(Collectors.groupingBy(m -> m, Collectors.counting())).entrySet().stream().map(e -> {
Map<String, Object> newMap = e.getKey();
newMap.put("count", e.getValue());
return newMap;
}).collect(Collectors.toList());
You can use the groupingBy method to manage aggregation, for example:
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D", "A");
Map<String, List<String>> map = list.stream().collect(Collectors.groupingBy(Function.identity()));
}
If you want more flexibility (for example to map the value and return a Set instead of a List) you can always use the groupingBy method with more parameters as specified in javadoc:
Map<City, Set<String>> namesByCity = people.stream().collect(Collectors.groupingBy(Person::getCity, mapping(Person::getLastName, toSet())));
Functions key and value you have defined in your code are not correct because they should operate on the elements of your list, and your elements are not Maps.
The following code works for me:
List<String> list = Arrays.asList("A", "B", "C", "D");
Map<String, List<String>> map = list.stream()
.collect(Collectors.toMap(Function.identity(), Arrays::asList));
First argument to Collectors.toMap defines how to make a key from the list element (leaving it as is), second argument defines how to make a value (making an ArrayList with a single element).
Because you have only one entry, then in this case, you need just to focus on the values, and for the key you can just use "1", for that you can create a Map like this :
Map<String, List<String>> result = new HashMap<>();
result.put("1", list.stream()
.filter(e -> e.containsKey("1"))
.flatMap(e -> e.values().stream())
.flatMap(List::stream)
.collect(Collectors.toList()));
Or as stated by Lino in the comment, you can also use :
Map<String, List<String>> result = list.stream()
.filter(e -> e.containsKey("1"))
.flatMap(e -> e.values().stream())
.flatMap(List::stream)
.collect(Collectors.groupingBy(t -> "1"));
As mentioned by @ernest_k you should declare
listas:List<Map<String, List<String>>>
You can use a groupingBy collector:
Map<String, List<String>> result = list.stream()
.map(m -> m.get("1"))
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(t -> "1"));
You can get rid of the intermediate filter with this. But this may be more confusing (and effectively does the same):
Map<String, List<String>> result = list.stream()
.map(m -> m.get("1"))
.flatMap(l -> l == null ? Stream.empty() : l.stream())
.collect(Collectors.groupingBy(t -> "1"));
I believe something like this should work:
Map<String,List<String>> map =
userList.stream()
.flatMap(user -> {
Map<String,String> um = new HashMap<>();
um.put("names",user.getName());
um.put("age",user.getAge());
um.put("org",user.getOrg());
return um.entrySet().stream();
}) // produces a Stream<Map.Entry<String,String>>
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
It converts each User to a Map<String,String> (containing the 3 required properties indexed by the required keys), and then groups the entries of all the user maps by their keys.
EDIT:
Here's another alternative that creates the Map.Entrys directly instead of creating the small HashMaps, so it should be more efficient:
Map<String,List<String>> map =
userList.stream()
.flatMap (user -> Stream.of (new SimpleEntry<>("names",user.getName()),
new SimpleEntry<>("age",user.getAge()),
new SimpleEntry<>("org",user.getOrg())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
Eran's showed you how you can accomplish this with streams. As you can hopefully see, it's incredibly ugly.
If your issue with your procedural version is the amount of code duplication, there are other ways besides streams that we can use to solve that problem.
I would refactor the collection to its own method:
private static List<String> getProperty(List<User> users, Function<User, String> getter) {
return users.stream().map(getter).collect(Collectors.toList());
}
Map<String,List<String>> map = new HashMap<>();
map.put("names", getProperty(userList, User::getName));
map.put("age", getProperty(userList, User::getAge));
map.put("org", getProperty(userList, User::getOrg));
You may do it like so:
Map<String, List<String>> locationMap = locations.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
A much more better approach would be,
private static final Pattern DELIMITER = Pattern.compile(":");
Map<String, List<String>> locationMap = locations.stream()
.map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
Update
As per the following comment, this can be further simplified to,
Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
Try this
Map<String, List<String>> locationMap = locations.stream()
.map(s -> new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));