Map data between two array list - java

I have data:
Item: {String name,String count}
List<Item> listA =[{"a",10},{"b",10},{"c",10},{"d",10},{"e",10},{"f",10}]
List<Item> listB =[{"b",1},{"d",3},{"f",4},{"h",5}]
I want map data from listB to listA so I used code:
for (int i = 0; i < listB.size(); i++) {
Item item= listB.get(i); // get element in listB
for (int j = 0; j < listA.size(); j++) {
if (item.getName().equals(listA.get(j).getName())) {
listA.get(j).setCount(item.getCount());
}
}
}
My result:
listA =[{"a",10},{"b",1},{"c",10},{"d",3},{"e",10},{"f",4}]
My code working but I want do it better. Because it will duplicate item in for of listA. How I can do it better? Please help me. Thank you so much.

I'm not sure of your Java version,
but if you are using a higher version than Java 8, could you try this code below?
// Map is useful to remove duplicate data,
// so we will convert the list type to map.
Map<String, Integer> mapA = listA.stream()
.collect(Collectors.toMap(Item::getName, Item::getCount));
Map<String, Integer> mapB = listB.stream()
.collect(Collectors.toMap(Item::getName, Item::getCount));
// Let's put the data from mapA to mapB
mapB.entrySet().stream()
.filter(entry -> mapA.containsKey(entry.getKey()))
.forEach(entry -> mapA.put(entry.getKey(), entry.getValue()));
// Your expected result is list type, like below,
// [{"a": 10},{"b": 1},{"c": 10},{"d": 3},{"e": 10},{"f": 4}]
// convert it to list again!
List<Item> list = mapA.entrySet().stream()
.map(o -> new Item(o.getKey(), o.getValue())).collect(Collectors.toList());

Instead of a List try to create a HashMap. Then, loop through the entries of the mapB
and update the mapA. It will automatically replace the values for keys that exist in the map and generate the entries that don't exist.
Example Code:
Map<String, Integer> mapA = createMapA() , mapB = createMapB();
mapB.entrySet().foreach(entry -> mapA.put(entry.getKey(), entry.getValue());
The lambda code style is in Java8 but the general idea remains the same if you have Java7.

Related

Remove duplicates from list based on duplicate index in another list

I have 2 Lists: Names & IDs.
There are cases where the same name will appear multiple times. For example:
Names = {'ben','david','jerry','tom','ben'}
IDs = {'123','23456','34567','123','123'}
I know I can use
Set<String> set = new LinkedHashSet<>( Names );
Names .clear();
Names .addAll( set );
In order to remove duplicates, however, it not what I want.
What I would like to do is to check where Names has a duplicate value which in this case will be the last value and then remove from IDs the value at that position so the final result will be:
Names = {'ben','david','jerry','tom'}
IDs = {'123','23456','34567','123'}
How can I get the index of the duplicated value in order to remove it from the second list? or is there some easy and fast way to do it?
I'm sure I can solve it by using a loop but I try to avoid it.
SOLUTION:
I changed the code to use:
Map<String, String> map = new HashMap<>();
When using:
map.put(name,id);
It might not do the job since there are cases where the same name has different it and it won't allow duplicate in the name so just changed to map.put(id,name) and it did the job.
Thank you
You could collect the data from both input arrays/lists into a set of pairs and then recollect the pairs back to two new lists (or clear and reuse existing names/IDs lists):
List<String> names = Arrays.asList("ben","david","jerry","tom","ben");
List<String> IDs = Arrays.asList("123","23456","34567","123","123");
// assuming that both lists have the same size
// using list to store a pair
Set<List<String>> deduped = IntStream.range(0, names.size())
.mapToObj(i -> Arrays.asList(names.get(i), IDs.get(i)))
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(deduped);
System.out.println("-------");
List<String> dedupedNames = new ArrayList<>();
List<String> dedupedIDs = new ArrayList<>();
deduped.forEach(pair -> {dedupedNames.add(pair.get(0)); dedupedIDs.add(pair.get(1)); });
System.out.println(dedupedNames);
System.out.println(dedupedIDs);
Output:
[[ben, 123], [david, 23456], [jerry, 34567], [tom, 123]]
-------
[ben, david, jerry, tom]
[123, 23456, 34567, 123]
You can collect as a map using Collectors.toMap then get the keySet and values from map for names and ids list.
List<String> names = Arrays.asList("ben","david","jerry","tom","ben");
List<String> ids = Arrays.asList("123","23456","34567","123","123");
Map<String, String> map =
IntStream.range(0, ids.size())
.boxed()
.collect(Collectors.toMap(i -> names.get(i), i -> ids.get(i),
(a,b) -> a, LinkedHashMap::new));
List<String> newNames = new ArrayList<>(map.keySet());
List<String> newIds = new ArrayList<>(map.values());
You can do map creation part using loop also
Map<String, String> map = new LinkedHashMap<>();
for (int i = 0; i < names.size(); i++) {
if(!map.containsKey(names.get(i))) {
map.put(names.get(i), ids.get(i));
}
}
You could add your names one by one to a set as long as Set.add returns true and if it returns false store the index of that element in a list (indices to remove). Then sort the indices list in reverse order and use List.remove(int n) on both your names list and id list:
List<String> names = ...
List<String> ids = ...
Set<String> set = new HashSet<>();
List<Integer> toRemove = new ArrayList<>();
for(int i = 0; i< names.size(); i ++){
if(!set.add(names.get(i))){
toRemove.add(i);
}
}
Collections.sort(toRemove, Collections.reverseOrder());
for (int i : toRemove){
names.remove(i);
ids.remove(i);
}
System.out.println(toRemove);
System.out.println(names);
System.out.println(ids);

Merge two list of type Long and add to existing map in java 8

I have two list both of type Long, say ListA and ListB.
I want to merge these into a Map<Long, Long> such that ListA becomes key and and ListB becomes value.
Here catch is I want to add these key value pair to an existing map.
I know how to parse the lists and return a new map object (using Collectors.toMap). My problem is to add to an existing map, may be something like:
Map<Long, Long> map = new HashMap<Long, Long>;
// ... entries added to map
ListA.stream().forEach(a -> {
map.put(a, <get 0th element of ListB somehow>);
});
Thanks in advance!
Supposing that those lists have the same size:
Map<Long, Long> map = IntStream.range(0, listA.size())
.boxed()
.collect(Collectors.toMap(listA::get, listB::get));
yourOtherMap.putAll(map);
Try this option:
Map<Long, Long> map = new HashMap<>();
IntStream.range(0, ListA.size())
.forEach(i -> {
map.put(ListA.get(i), ListB.get(i));
});
Demo
But honestly, I see nothing wrong here with using a regular pre Java 8 enhanced for loop:
// assuming both lists have the same size
for (int i=0; i < ListA.size(); ++i) {
map.put(ListA.get(i), ListB.get(i);
}
It's concise, easy to read and maintain, and won't turn the head of anyone reviewing your code.

Collect to map the order/position value of a sorted stream

I am sorting a populated set of MyObject (the object has a getName() getter) in a stream using a predefined myComparator.
Then once sorted, is there a way to collect into a map the name of the MyObject and the order/position of the object from the sort?
Here is what I think it should look like:
Set<MyObject> mySet; // Already populated mySet
Map<String, Integer> nameMap = mySet.stream()
.sorted(myComparator)
.collect(Collectors.toMap(MyObject::getName, //HowToGetThePositionOfTheObjectInTheStream));
For example, if the set contain three objects (object1 with name name1, object2 with name name2, object3 with name name3) and during the stream they get sorted, how do I get a resulting map that looks like this:
name1, 1
name2, 2
name3, 3
Thanks.
A Java Stream doesn't expose any index or positioning of elements, so I know no way of replacing /*HowToGetThePositionOfTheObjectInTheStream*/ with streams magic to obtain the desired number.
Instead, one simple way is to collect to a List instead, which gives every element an index. It's zero-based, so when converting to a map, add 1.
List<String> inOrder = mySet.stream()
.sorted(myComparator)
.map(MyObject::getName)
.collect(Collectors.toList());
Map<String, Integer> nameMap = new HashMap<>();
for (int i = 0; i < inOrder.size(); i++) {
nameMap.put(inOrder.get(i), i + 1);
}
Try this one. you could use AtomicInteger for value of each entry of map. and also to guarantee order of map use LinkedHashMap.
AtomicInteger index = new AtomicInteger(1);
Map<String, Integer> nameMap = mySet.stream()
.sorted(myComparator)
.collect(Collectors
.toMap(MyObject::getName, value -> index.getAndIncrement(),
(e1, e2) -> e1, LinkedHashMap::new));
The simplest solution would be a loop, as a formally correct stream solution that would also work in parallel requires a nontrivial (compared to the rest) merge functions:
Map<String,Integer> nameMap = mySet.stream()
.sorted(myComparator)
.collect(HashMap::new, (m, s) -> m.put(s.getName(), m.size()),
(m1, m2) -> {
int offset = m1.size();
m2.forEach((k, v) -> m1.put(k, v + offset));
});
Compare with a loop/collection operations:
List<MyObject> ordered = new ArrayList<>(mySet);
ordered.sort(myComparator);
Map<String, Integer> result = new HashMap<>();
for(MyObject o: ordered) result.put(o.getName(), result.size());
Both solutions assume unique elements (as there can be only one position). It’s easy to change the loop to detect violations:
for(MyObject o: ordered)
if(result.putIfAbsent(o.getName(), result.size()) != null)
throw new IllegalStateException("duplicate " + o.getName());
Dont use a stream:
List<MyObject> list = new ArrayList<>(mySet);
list.sort(myComparator);
Map<String, Integer> nameMap = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
nameMap.put(list.get(i).getName(), i);
}
Not only will this execute faster than a stream based approach, everyone knows what's going on.
Streams have their place, but pre-Java 8 code does too.

Overwriting values in a HashMap that are in an ArrayList<String>

Let's say I have a HashMap with String keys and Integer values:
map = {cat=1, kid=3, girl=3, adult=2, human=5, dog=2, boy=2}
I want to switch the keys and values by putting this information into another HashMap. I know that a HashMap cannot have duplicate keys, so I tried to put the information into a HashMap with the Integer for the keys that would map to a String ArrayList so that I could potentially have one Integer mapping to multiple Strings:
swap = {1=[cat], 2=[adult, dog, boy], 3=[kid, girl], 5=[human]}
I tried the following code:
HashMap<Integer, ArrayList<String>> swap = new HashMap<Integer, ArrayList<String>>();
for (String x : map.keySet()) {
for (int i = 0; i <= 5; i++) {
ArrayList<String> list = new ArrayList<String>();
if (i == map.get(x)) {
list.add(x);
swap.put(i, list);
}
}
}
The only difference in my code is that I didn't hard code the number 5 into my index; I have a method that finds the highest integer value in the original HashMap and used that. I know it works correctly because I get the same output even if I hard code the 5 in there, I just didn't include it to save space.
My goal here is to be able to do this 'reversal' with any set of data, otherwise I could just hard code the value. The output I get from the above code is this:
swap = {1=[cat], 2=[boy], 3=[girl], 5=[human]}
As you can see, my problem is that the value ArrayList is only keeping the last String that was put into it, instead of collecting all of them. How can I make the ArrayList store each String, rather than just the last String?
With Java 8, you can do the following:
Map<String, Integer> map = new HashMap<>();
map.put("cat", 1);
map.put("kid", 3);
map.put("girl", 3);
map.put("adult", 2);
map.put("human", 5);
map.put("dog", 2);
map.put("boy", 2);
Map<Integer, List<String>> newMap = map.keySet()
.stream()
.collect(Collectors.groupingBy(map::get));
System.out.println(newMap);
The output will be:
{1=[cat], 2=[adult, dog, boy], 3=[kid, girl], 5=[human]}
you are recreating the arrayList for every iteration and i can't figure out a way to do it with that logic, here is a good way though and without the need to check for the max integer:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
List<String> get = swap.get(value);
if (get == null) {
get = new ArrayList<>();
swap.put(value, get);
}
get.add(key);
}
Best way is to iterate over the key set of the original map.
Also you have to asure that the List is present for any key in the target map:
for (Map.Entry<String,Integer> inputEntry : map.entrySet())
swap.computeIfAbsent(inputEntry.getValue(),()->new ArrayList<>()).add(inputEntry.getKey());
This is obviously not the best solution, but approaches the problem the same way you did by interchanging inner and outer loops as shown below.
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("cat", 1);
map.put("kid", 3);
map.put("girl", 3);
map.put("adult", 2);
map.put("human", 5);
map.put("dog", 2);
map.put("boy", 2);
HashMap<Integer, ArrayList<String>> swap = new HashMap<Integer, ArrayList<String>>();
for (Integer value = 0; value <= 5; value++) {
ArrayList<String> list = new ArrayList<String>();
for (String key : map.keySet()) {
if (map.get(key) == value) {
list.add(key);
}
}
if (map.containsValue(value)) {
swap.put(value, list);
}
}
Output
{1=[cat], 2=[adult, dog, boy], 3=[kid, girl], 5=[human]}
Best way I can think of is using Map.forEach method on existing map and Map.computeIfAbsent method on new map:
Map<Integer, List<String>> swap = new HashMap<>();
map.forEach((k, v) -> swap.computeIfAbsent(v, k -> new ArrayList<>()).add(k));
As a side note, you can use the diamond operator <> to create your new map (there's no need to repeat the type of the key and value when invoking the map's constructor, as the compiler will infer them).
As a second side note, it's good practice to use interface types instead of concrete types, both for generic parameter types and for actual types. This is why I've used List and Map instead of ArrayList and HashMap, respectively.
Using groupingBy like in Jacob's answer but with Map.entrySet for better performance, as suggested by Boris:
// import static java.util.stream.Collectors.*
Map<Integer, List<String>> swap = map.entrySet()
.stream()
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
This uses two more methods of Collectors: mapping and toList.
If it wasn't for these two helper functions, the solution could look like this:
Map<Integer, List<String>> swap = map.entrySet()
.stream()
.collect(
groupingBy(
Entry::getValue,
Collector.of(
ArrayList::new,
(list, e) -> {
list.add(e.getKey());
},
(left, right) -> { // only needed for parallel streams
left.addAll(right);
return left;
}
)
)
);
Or, using toMap instead of groupingBy:
Map<Integer, List<String>> swap = map.entrySet()
.stream()
.collect(
toMap(
Entry::getValue,
(e) -> new ArrayList<>(Arrays.asList(e.getKey())),
(left, right) -> {
left.addAll(right);
return left;
}
)
);
It seams you override the values instrad of adding them to the already creared arraylist. Try this:
HashMap<Integer, ArrayList<String>> swapedMap = new HashMap<Integer, ArrayList<String>>();
for (String key : map.keySet()) {
Integer swappedKey = map.get(key);
ArrayList<String> a = swapedMap.get(swappedKey);
if (a == null) {
a = new ArrayList<String>();
swapedMap.put(swappedKey, a)
}
a.add(key);
}
I didn't have time to run it (sorry, don't have Java compiler now), but should be almost ok :)
You could use the new merge method in java-8 from Map:
Map<Integer, List<String>> newMap = new HashMap<>();
map.forEach((key, value) -> {
List<String> values = new ArrayList<>();
values.add(key);
newMap.merge(value, values, (left, right) -> {
left.addAll(right);
return left;
});
});

How to GROUP BY same strings in Java

I have got an Arraylist of strings and I need to return the Arraylist indexes of strings that are the same.
For example
Arraylist[0]: IPAddress
Arraylist[1]: DomainName
Arraylist[2]: IPAddress
Arraylist[3]: Filesize
The output should be:
Arraylist[0]
IPAddress|0,2 //0,2 denotes the arraylist index that is of the same
Arraylist[1]
DomainName|1
Arraylist[2]
Filesize|3
Any idea how can this be achieved?
What I have done is:
for(int i=0; i<arr.size(); i++){
if(arr.get(i).equals(arr.size()-1)){
//print index
}
}
With Java8 streams
List<String> strings = Arrays.asList("IPAddress", "DomainName", "IPAddress", "Filesize");
Map<String, List<Integer>> map = IntStream.range(0, strings.size()).boxed().collect(Collectors.groupingBy(strings::get));
System.out.println(map);
output
{DomainName=[1], Filesize=[3], IPAddress=[0, 2]}
To get the results in ordered
Map<String, List<Integer>> map = IntStream.range(0, strings.size())
.boxed()
.collect(Collectors.groupingBy(strings::get, LinkedHashMap::new, Collectors.toList()));
The mechanical steps are fairly straightforward:
Get a collection which can support a key (which is the string in your list) and a list of values representing the indexes in which they occur (which would be another ArrayList).
If the element exists in the collection, simply add the index to its value.
Otherwise, create a new list, add the index to that, then add that to the collection.
Here is some sample code below.
final List<String> list = new ArrayList<String>() {{
add("IPAddress");
add("DomainName");
add("IPAddress");
add("Filesize");
}};
final Map<String, List<Integer>> correlations = new LinkedHashMap<>();
for (int i = 0; i < list.size(); i++) {
final String key = list.get(i);
if (correlations.containsKey(key)) {
correlations.get(key).add(i);
} else {
final List<Integer> indexList = new ArrayList<>();
indexList.add(i);
correlations.put(key, indexList);
}
}
Any optimizations to the above are left as an exercise for the reader.

Categories