Java: List<List<String>> list = new ArrayList<>(); - java

How I can group all lists in list which contains same exact value.
List<List<String>> list = new ArrayList<>();
This list contains list1 list2 list3 and etc....
I want to find if list1.get(0) is the same as list2.get(0) if no check with list3.get(0) and etc...
Later I need to group lists if I find the same values in each.
For example if true add list1 and list3 and others which were found to
List<List<String>> list2 = new ArrayList<>();
Now check with list2.get(0) if equal to others if yes group them and add them to anoter:
List<List<String>> list3 = new ArrayList<>();
What I achieved so far:
private static void findEqualLists(List<List<String>> list) {
int i = 0;
for (List<String> list1 : list) {
if (!Collections.disjoint(list1, list.get(i))) {
System.out.println(list1.get(0)+list.get(i).get(0));
}else{
System.out.println(list1.get(0)+list.get(i).get(0));
}
i++;
}
}
Value exmaple:
list = {{2017-02,jhon,car},{2017-03,maria,car},{2017-03, boy, car}, {2017-01,arya, car}, {2017-02, girl, car}}
Output:
Group1:
2017-03,maria,car
2017-03, boy, car
Group2:
2017-02,jhon,car
2017-02, girl, car
Group3
2017-01,arya, car

You want Collectors.groupingBy:
private static Map<String, List<List<String>>>
findEqualLists(List<List<String>> list) {
return list.stream().collect(Collectors.groupingBy(l -> l.get(0)));
}
The returned Map will use l.get(0) as a unique key, with each corresponding value being a List of only those Lists whose first element matches that key.

Related

Compare two lists and increase the counter on a match with java streams

I have two lists. list1 contains some citiys.
list2 contains sub-lists. Each sub-list contains the countries already visited by a person (one sub-list = the countries visited by one person). In the example Person1 has traveld to Rom, Amsterdam and Vienna, Person2 to Amsterdam, Barcelona and Milan ...
I would like to know how many people have already been to the countries in the first list. There should be no double counting. So if Person1 has already been to two countries from list1, it should only be counted once.
I would like to implement this with Java Streams. Does anyone know how I can do this?
list1 = ["Barcelona", "Milan", "Athens"];
list2 = [["Rom", "Amsterdam", "Vienna"], ["Amsterdam", "Barcelona", "Milan"], ["Prais", "Athens"], ["Istanbul", "Barcelona", "Milan", "Athens"]];
//The expected result for this example is: 3
//Both lists already result from a stream (Collectors.toList())
Thanks a lot!
You can try something like this:
private static final List<String> CITIES = List.of("Barcelona", "Milan", "Athens");
private static final List<List<String>> VISITED_CITIES = List.of(
List.of("Rome", "Amsterdam", "Vienna"),
List.of("Amsterdam", "Barcelona", "Milan"),
List.of("Paris", "Athens"),
List.of("Instabul", "Barcelon", "Milan", "Athens")
);
public static void main(String... args) {
var count = VISITED_CITIES
.stream()
.flatMap(visited -> visited.stream().filter(CITIES::contains))
.distinct()
.count();
System.out.println(count);
}
With this iteration you will get the expected result of 3. However you can modify your code to also collect into a Map that will show frequencies (if you remove the distinct intermediate step), something like this:
var count = VISITED_CITIES
.stream()
.flatMap(visited -> visited.stream().filter(CITIES::contains))
.collect(Collectors.groupingBy(Function.identity()));
Have a look at the mapToInt() and sum() function.
List<String> list1 = List.of("Barcelona", "Milan", "Athens");
List<List<String>> list2 = List.of(List.of("Rom", "Amsterdam", "Vienna"),
List.of("Amsterdam", "Barcelona", "Milan"),
List.of("Prais", "Athens"),
List.of("Istanbul", "Barcelona", "Milan", "Athens"));
int result = list2.stream().mapToInt(person -> person.stream().anyMatch(list1::contains) ? 1 : 0).sum();
What I do here is create a stream of all persons and then map each person to either 1 or 0 depending on if any of their visited countries is contained in list1.
This is identical with the following for-loop example:
int result = 0;
for (List<String> person : list2)
{
int i = 0;
for (String visited : person)
{
if (list1.contains(visited))
{
i = 1;
break;
}
}
result += i;
}

How to merge two corresponding values of two different variables in arraylist?

I want to merge two corresponding values of two different variables with comma separator in a row :
like
Plate Numbers(Output) : MH 35353, AP 35989, NA 24455, DL 95405.
There is two different variables one is plate State and another is plate Number, I want to merge them together with their corresponding values like 1st values of plate State with 1st value of plate Number after that comma then so on..
I tried this code snippet but didn't work :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
list1.addAll(list2);
use this :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
Iterator iterable = list2.iterator();
List<String> list3 =list1.stream()
.map(x->{
x= x+" "+((String) iterable.next());
return x;})
.collect(Collectors.toList());
String output = String.join(", ", list3);
System.out.println(output);
From ArrayList#addAll Javadoc:
Appends all of the elements in the specified collection to the end of this list[...]
This is not what you want, because you actually don't want to append the objects, you want to merge the String of the first list with the String from the second list. So in a sense, not merge the List but merge the objects (Strings) in the lists.
The easiest (most beginner friendly) solution would be to just create a simple helper method yourself, that does what you need.
Something like this:
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA");
list1.add("DL");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
ArrayList<String> combined = combinePlateNumbers(list1, list2);
System.out.println(combined);
}
private static ArrayList<String> combinePlateNumbers(List<String> list1, List<String> list2) {
ArrayList<String> result = new ArrayList<>();
if (list1.size() != list2.size()) {
// lists don't have equal size, not compatible
// your decision on how to handle this
return result;
}
// iterate the list and combine the strings (added optional whitespace here)
for (int i = 0; i < list1.size(); i++) {
result.add(list1.get(i).concat(" ").concat(list2.get(i)));
}
return result;
}
Output:
[MH 35353, AP 35989, NA 24455, DL 95405]

Unique set from ArrayList of ArrayList

Hi I have an arraylist of arraylist in this format:
[[val1, val2],[val3,val4],[val1,val2],[val1,val5]]
and would like to get the unique set of arraylists:
[[val1, val2],[val3,val4],[val1,val5]]
I have tried the following:
Set<String> uniques = new HashSet<>();
for (ArrayList<String> sublist : mappedEntities) {
uniques.addAll(sublist);
}
but this merges all the values of the internal arraylist together
can use Java 8 Collection Stream Distinct,
return in Set datatype :
Set<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toSet());
if you want return in List :
List<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toList());
Why not simply put them in a Set like this?
Set<List<String>> uniques = new HashSet<>(mappedEntities);
Your mistake is that you are flattening the inner lists and putting their items in the set separately.
The issue here is that you need a Set of ArrayList Set<ArrayList<String>>, but you are using a Set of Strings Set<String> instead.
Given the list :
List<List<String>> mappedEntities = Arrays.asList(Arrays.asList("val1", "val2"),
Arrays.asList("val3", "val4"),
Arrays.asList("val1", "val2"),
Arrays.asList("val1", "val5"));
All you need to do is just declare the set and use the addAll().
Set<List<String>> mySet = new HashSet<>();
mySet.addAll(mappedEntities);
Since a set can hold only unique values, all duplicates will not be added to the set (No need to explicitly check this). You can now print it out :
mySet.forEach(System.out::println);
Or more simply, initialize the HashSet using the list mappedEntities :
Set<List<String>> mySet = new HashSet<>(mappedEntities);
I am beginner on STACKOVERFLOW but i to try solve your problem
I think you want like this..
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int n = 3;
// Here aList is an ArrayList of ArrayLists
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >(n);
// Create n lists one by one and append to the
// master list (ArrayList of ArrayList)
ArrayList<String> a1 = new ArrayList<String>();
a1.add("1");
a1.add("2");
aList.add(a1);
ArrayList<String> a2 = new ArrayList<String>();
a2.add("11");
a2.add("22");
aList.add(a2);
ArrayList<String> a3 = new ArrayList<String>();
a3.add("1");
a3.add("2");
aList.add(a3);
Set<ArrayList<String>> uniques = new HashSet<ArrayList<String>>();
for (ArrayList<String> sublist : aList) {
uniques.add(sublist);
}
System.out.println("Your Answer");
for (ArrayList<String> x : uniques)
System.out.println(x);
}
}
try this code:
public class B {
public static void main(String[] args) throws Exception {
List<List<String>> list= Arrays.asList(
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c","d"));
Set<List<String>> uniques = new HashSet<>();
for (List<String> sublist : list) {
if(!uniques.contains(sublist))
uniques.add(sublist);
}
System.out.println(uniques);
}
}
output:
[[a, b, c], [a, b, c, d]]

How can I split an ArrayList into two new ArrayLists?

I have on ArrayList which contains data like this: 13-ITEM,14-ITEM,15-ITEMGROUP (with a hyphen (-) as the separator).
I want to split this list into two new ArrayLists:
ArrayList-1 containing the ids: [13,14,15..]
ArrayList-2 containing the Strings: [ITEM,ITEM,ITEMGROUP...]
I am new to Java. Thanks in advance.
You can use String#indexOf(char) to find the index in the String of the separator then use String#substring to extract the sub strings, as next:
List<String> list = Arrays.asList("13-ITEM","14-ITEM","15-ITEMGROUP");
List<String> list1 = new ArrayList<>(list.size());
List<String> list2 = new ArrayList<>(list.size());
for (String s : list) {
int index = s.indexOf('-');
// Add what we have before the separator in list1
list1.add(s.substring(0, index));
// Add what we have after the separator in list2
list2.add(s.substring(index + 1));
}
System.out.printf("List 1 = %s, List 2 = %s%n", list1, list2);
Output:
List 1 = [13, 14, 15], List 2 = [ITEM, ITEM, ITEMGROUP]
Split each entry and add the parts to the different lists. If the texts contain more -s, then use substring.
ArrayList<String> input = ...
List<String> output1 = new ArrayList<>(input.size());
List<String> output2 = new ArrayList<>(input.size());
for(String item:input){
String[] splitted = item.split("-");
output1.add(splitted[0]);
output2.add(splitted[1]);
}
You can use the following code
List<String> list = Arrays.asList("13-ITEM", "14-ITEM", "15-ITEMGROUP");
list.stream().map(p -> p.substring(0, p.indexOf('-'))).forEach(System.out::println);
list.stream().map(p -> p.substring(p.indexOf('-') + 1)).forEach(System.out::println);
If you split your concerns like this (each list is created using different logic), you will have a possibility to encapsulate code further. For example you can add some exception handling.
private static Function<String, String> getFunction() {
return new Function<String, String>() {
#Override
public String apply(String p) {
return p.substring(0, p.indexOf('-'));
}
};
}

How to add elements to a list object by iterating 3 different list objects in java?

I am having three lists i.e., list1,list2,list3 my code works fine in getting the following list outputs:
o/p
Getting the list1 objects [man, animal, jackel]
Getting the list2 objects [1, 2, 3]
Getting the list3 objects [bobby, lion, dilip]
Now I am trying to get list4 as [man,1,bobby]
AND also list5 as [man,1,bobby , animal,2,lion , jackel,3,dilip]
Here is my code which gives the output of list1, list2, list3
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
List<String> list3 = new ArrayList<String>();
String splitstring="man,animal,jackel";
String splitid="1,2,3";
String splitscreenname="bobby,lion,dilip";
String[] arrsplitstring=splitstring.split(",");
String[] arrssplitid=splitid.split(",");
String[] arrsplitedscreenname=splitscreenname.split(",");
List<String> wordList = Arrays.asList(arrsplitstring);
List<String> wordid = Arrays.asList(arrssplitid);
List<String> wordscreenlist = Arrays.asList(arrsplitedscreenname);
for (int i=0;i<wordList.size();i++){
list1.add(wordList.get(i));
}
System.out.println("Getting the list1 objects " +list1 );
for(int i=0;i<wordid.size();i++){
list2.add(wordid.get(i));
}
System.out.println("Getting the list2 objects " +list2);
for (int i=0;i<wordscreenlist.size();i++){
list3.add(wordscreenlist.get(i));
}
System.out.println("Getting the list3 objects " +list3);
I'm Trying it by iteration of each list object but I almost lost in finding the solution.
Thanks in advance
What you want to do is iterate one of the Lists and add items from all 3 Lists to your new List.
What you probably want to actually do is have an Animal object of sorts, containing properties from the 3 original Lists.
Here's an example (note: Java 7 syntax here):
// initializing lists
List<String> animals = new ArrayList<>(
Arrays.asList(new String[]{"man", "animal", "jackal"})
);
List<Number> numbers = new ArrayList<>(
Arrays.asList(new Number[]{1, 2, 3})
);
List<String> names = new ArrayList<>(
Arrays.asList(new String[]{"bobby", "lion", "dilip"})
);
// sequential list of objects
List<Object> allObjects = new ArrayList<>();
// class describing an "animal", wrapping the 3 properties
class Animal {
String type;
Number number;
String name;
Animal(String type, Number number, String name) {
this.type = type;
this.number = number;
this.name = name;
}
// fancy String representation
#Override
public String toString() {
return String.format("Type: %s, Number: %d, Name: %s%n", type, number, name);
}
}
// list of Animals
List<Animal> allAnimals = new ArrayList<>();
// iterating the first list (arbitrary choice)
for (int i = 0; i < animals.size(); i++) {
// adding sequentially to objects list
allObjects.add(animals.get(i));
// TODO check for index out of bounds
allObjects.add(numbers.get(i));
allObjects.add(names.get(i));
// adding to animals list sequentially with 3 props each animal
allAnimals.add(new Animal(animals.get(i), numbers.get(i), names.get(i)));
}
// printing out values
System.out.println("All objects...");
System.out.println(allObjects);
System.out.println("All animals...");
System.out.println(allAnimals);
Output
All objects...
[man, 1, bobby, animal, 2, lion, jackal, 3, dilip]
All animals...
[Type: man, Number: 1, Name: bobby
, Type: animal, Number: 2, Name: lion
, Type: jackal, Number: 3, Name: dilip
]
The first one could be something like this:
List<String> list4 = new ArrayList<String>();
// Check the three lists have the same number of elements.
// If not, return (you have to show and error)
if (! (
(wordListIt.size() == wordidIt.size() )
&&
(wordidIt.size() == wordscreenlistIt.size() )
) ) return;
Iterator<String> wordListIt = wordList.iterator();
Iterator<String> wordidIt = wordid.iterator();
Iterator<String> wordscreenlistIt = wordscreenlist.iterator();
while (wordListIt.hasNext()) {
list4.add(wordListIt.next());
list4.add(wordidIt.next());
list4.add(wordscreenlistIt.next());
break; // exit the while, because you only want the first element.
}
The second one could be something like this:
List<String> list5 = new ArrayList<String>();
// Check the three lists have the same number of elements.
// If not, return (you have to show and error)
if (! (
(wordListIt.size() == wordidIt.size() )
&&
(wordidIt.size() == wordscreenlistIt.size() )
) ) return;
Iterator<String> wordListIt = wordList.iterator();
Iterator<String> wordidIt = wordid.iterator();
Iterator<String> wordscreenlistIt = wordscreenlist.iterator();
while (wordListIt.hasNext()) {
list5.add(wordListIt.next());
list5.add(wordidIt.next());
list5.add(wordscreenlistIt.next());
}
You need to iterate over the elements of each list to get your desired result..
List<String> list4 = new ArrayList<String>();
list4.add(list1.get(0));
list4.add(list2.get(0));
list4.add(list3.get(0));
List<String> list5 = new ArrayList<String>();
for(int ctr=0;ctr<list3.size();ctr++)
{
list5.add(list1.get(ctr));
list5.add(list2.get(ctr));
list5.add(list3.get(ctr));
}

Categories

Resources