Java-how to split one list in two lists - java

Who can help me and give me a code that split an list contains positif and negatif values in two list :the first list contains neagtif values and second list contains positf values without using java library.help me

Why not a little help!
Assuming your List contains integers.
List<Integer> integers = listOfIntegers();
List<Integer> positive = new ArrayList<>();
List<Integer> negative = new ArrayList<>();
for (Integer i : integers) {
if (i >= 0)
positive.add(i);
else
negative.add(i);
}
The next time you need to specify more information. Furthermore, you must ask about a particular problem in your code and not for a complete solution.

Related

Arraylist Comparison using one loop

It has been a long since something came to my mind while starting to code and using lists or array lists. When comparing values of one array to every other elements in another array, I used to do it in two for loops since it was the easiest way to do that.but recently I came to know that it increases much time complexity, I thought about another solution.can anyone help me in solving this case using any algorithm. I am using java.but solution in any language would be fine. just the algorithm to do that is needed. Thanks in advance.
This is what i am doing:
a1 = [1,2,3,4,5]
b1 = [9,5,4,3,8,3,7]
I want to check how much time an element in a1 occurs in b1
So what i am doing is:
count = 0;
for(int i = 0;i <a1.length;i++)
{
for(j=0;j<b1.length;j++)
{
if (a1[i] == b1[j])
{
count = count+1;
}
}
}
print("count is" count);
Theres no need of loop to obtain what you want
ArrayList<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
l1.add(4);
l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();
l2.add(9);
l2.add(5);
l2.add(4);
l2.add(3);
l2.add(8);
l2.add(3);
l2.add(7);
ArrayList<Integer> lFiltered = new ArrayList<Integer>(l2);
lFiltered.removeAll(l1);
int Times = l2.size() - lFiltered.size();
System.out.println("number of migrants : " + Times);
Suffice it to to generate from l2 a list without elements and l1 and to count elements which have been removed
Use hashing, e.g. using a Set or Map
If you want to compare the objects as a whole:
properly implement equals and hashcode for your class (if not implemented already)
put all the elements of list A into a Set, then see which elements from list B are in that Set
If you just want to compare objects by some attribute:
define a method that maps the objects to that attribute (or combination of attriutes, e.g. as a List)
create a Map<KeyAttributeType, List<YourClass>> and for each element from list A, add the element to that Map: map.get(getKey(x)).add(x)
for each element from list B, calculate the value of the key function and get the elements it "matches" from the map: matches = map.get(getKey(y))
Given your code, your case seems to be a bit different, though. You have lists or arrays of numbers, so no additional hashing is necessary, and you do not just want to see which items "match", but count all combinations of matching items. For this, you could create a Map<Integer, Long> to count how often each element of the first list appears, and then get the sum of those counts for the elements from the second list.
int[] a1 = {1,2,3,4,5};
int[] b1 = {9,5,4,3,8,3,7};
Map<Integer, Long> counts = IntStream.of(b1).boxed()
.collect(Collectors.groupingBy(x -> x, Collectors.counting()));
System.out.println(counts); // {3=2, 4=1, 5=1, 7=1, 8=1, 9=1}
long total = IntStream.of(a1).mapToLong(x -> counts.getOrDefault(x, 0L)).sum();
System.out.println(total); // 4
Of course, instead of using the Stream API you can just as well use regular loops.
Use ArrayLists.
To compare the content of both arrays:
ArrayList<String> listOne = new ArrayList<>(Arrays.asList(yourArray1);
ArrayList<String> listTwo = new ArrayList<>(Arrays.asList(yourArray);
listOne.retainAll(listTwo);
System.out.println(listOne)
To find missing elements:
listTwo.removeAll(listOne);
System.out.println(listTwo);
To enumerate the Common elements:
//Time complexity is O(n^2)
int count =0;
for (String element : listOne){
for (String element2: listTwo){
if (element.equalsIgnoreCase(elemnt2){
count += 1;
}
}
}

Checking if an ArrayList contains more than 1 of the same integer and removing them from the list?

I ran into a seemingly simple problem that I haven't been able to figure out. Basically, my list holds a number of ints which represent different items, which works fine, but I need to be able to check if the list contains the same integer more than once and then remove them from the list.
if (myList.contains(100)) { // I want to check if the int '100' exists in myList twice
myList.remove(new Integer(100)); // I want to remove the 2 aforementioned duplicate integers
}
Apologies if my explanation wasn't the clearest. Thanks in advance!
EDIT: To clarify, I want the list to contain duplicates but I want to be able to check if the duplicate exists X times and then remove those instances from the list.
i.e.
I might want to add the int 100 7 times, and then later check if it exists twice and then remove 2 instances of it from the list only.
you can create a method to accomplish the task at hand, something along the lines of this:
private static boolean removeSpecfiedNumber(int number,int numberOfTimes, List<Integer> integerList){
if(integerList.stream().filter(x -> x == number).count() >= numberOfTimes){
for (int i = 0; i < numberOfTimes; i++) {
integerList.remove((Integer)number);
}
return true;
}
return false;
}
The parameter number is the number you want to check its occurrences i.e. 100 in your case.
The parameter numberOfTimes is the number of times you want to remove that element from the list.
The parameter integerList is, of course, the list you want to remove the elements from.
Let's take the code below as an example:
List<Integer> myList = new ArrayList<>();
myList.add(100);
myList.add(200);
myList.add(100);
myList.add(100);
myList.add(100);
myList.add(100);
myList.add(100);
myList.add(100);
removeSpecfiedNumber(100,2,myList);
System.out.println(myList);
this will remove 100 twice from myList and should, therefore, yield the elements below:
[200, 100, 100, 100, 100, 100]
The method return type can be void if you want, However, the return type of boolean can come in handy at times hence I've used that approach.
Also, you need not use the static modifier if you're dealing with objects, therefore you can remove it.
1) myList.remove(new Integer(100)); will remove only the first occurrence that is equals to 100.
You should loop on remove() while the list contains still an object with the same value.
2) To know if the list contains more than once the object, you could use indexOf() and lastIndexOf() .
If these are distinct, it means that you have more than one element.
So according to your requirement, you can remove all of them with the method described in the point 1.
Integer valueToCheck = 100;
if ( myList.indexOf(valueToCheck) != myList.lastIndexOf(valueToCheck) ) {
while (myList.contains(valueToCheck)){
myList.remove(valueToCheck);
}
}
You can use a Set which does not allowed duplicate keys e.g.
Set<Ineger> foo = new HashSet<>(myList);
And you can create a new List from that or use it as it is.
Starting java 8 you can use java stream api in such way:
List<Integer> i = new ArrayList<Integer>();
i.add(1);
i.add(2);
i.add(3);
i.add(1);
List<Integer> collect = i.stream().distinct().collect(Collectors.toList());
NOTE: new list will be created.

How to find the number of unique words in array list

So I am trying to create an for loop to find unique elements in a ArrayList.
I already have a ArrayList stored with user input of 20 places (repeats are allowed) but I am stuck on how to count the number of different places inputted in the list excluding duplicates. (i would like to avoid using hash)
Input:
[park, park, sea, beach, town]
Output:
[Number of unique places = 4]
Heres a rough example of the code I'm trying to make:
public static void main(String[] args) {
ArrayList<City> place = new ArrayList();
Scanner sc = new Scanner(System.in);
for(...) { // this is just to receive 20 inputs from users using the scanner
...
}
# This is where i am lost on creating a for loop...
}
you can use a Set for that.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Store the list data to the Set.Set will not have duplicates in it, so the size of set will be the elements without duplicates.
use this method to get the set size.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
Sample Code.
List<String> citiesWithDuplicates =
Arrays.asList(new String[] {"park", "park", "sea", "beach", "town"});
Set<String> cities = new HashSet<>(citiesWithDuplicates);
System.out.println("Number of unique places = " + cities.size());
If you are able to use Java 8, you can use the distinct method of Java streams:
int numOfUniquePlaces = list.stream().distinct().count();
Otherwise, using a set is the easiest solution. Since you don't want to use "hash", use a TreeSet (although HashSet is in most cases the better solution). If that is not an option either, you'll have to manually check for each element whether it's a duplicate or not.
One way that comes to mind (without using Set or hashvalues) is to make a second list.
ArrayList<City> places = new ArrayList<>();
//Fill array
ArrayList<String> uniquePlaces = new ArrayList<>();
for (City city : places){
if (!uniquePlaces.contains(city.getPlace())){
uniquePlaces.add(city.getPlace());
}
}
//number of unique places:
int uniqueCount = uniquePlaces.size();
Note that this is not super efficient =D
If you do not want to use implementations of Set or Map interfaces (that would solve you problem with one line of code) and you want to stuck with ArrayList, I suggest use something like Collections.sort() method. It will sort you elements. Then iterate through the sorted array and compare and count duplicates. This trick can make solving your iteration problem easier.
Anyway, I strongly recommend using one of the implementations of Set interface.
Use following answer. This will add last duplicate element in distinct list if there are multiple duplicate elements.
List<String> citiesWithDuplicates = Arrays.asList(new String[] {
"park", "park", "sea", "beach", "town", "park", "beach" });
List<String> distinctCities = new ArrayList<String>();
int currentIndex = 0;
for (String city : citiesWithDuplicates) {
int index = citiesWithDuplicates.lastIndexOf(city);
if (index == currentIndex) {
distinctCities.add(city);
}
currentIndex++;
}
System.out.println("[ Number of unique places = "
+ distinctCities.size() + "]");
Well if you do not want to use any HashSets or similar options, a quick and dirty nested for-loop like this for example does the trick (it is just slow as hell if you have a lot of items (20 would be just fine)):
int differentCount=0;
for(City city1 : place){
boolean same=false;
for(City city2 : place){
if(city1.equals(city2)){
same=true;
break;
}
}
if(!same)
differentCount++;
}
System.out.printf("Number of unique places = %d\n",differentCount);

How to find total number of different items within an arraylist.

I've done some searching but I wasn't able to find a valid solution. I have an arraylist storing Strings such as gum, socks, OJ, dog food...
I am having trouble iterating the list to determine the total number of differnt types of items.
ie.
ArrayList<String> Store = new ArrayList<String>();
this.Store.add("Gum");
this.Store.add("Gum");
this.Store.add("Socks");
this.Store.add("Candy");
The list has 4 total items, but only three different kinds of items (Gum, Sucks, Candy).
How would I design a method to calculate the 3?
What Bhesh Gurung said, but in code:
int numUnique = new HashSet<String>(Store).size();
If what you actually have is StoreItems and need to go through getName() then I would do
Set<String> itemNames = new HashSet<String>();
for (StoreItem item : Store)
itemNames.add(item.getName());
int numUnique = itemNames.size();
Use a Set (HashSet) whose size will give you what you are looking for.
This looks like a homework... So, if you do not understand the HashSet solution proposed above (or doning the same with a HashMap), think about doing something like this:
Create a new ArrayList
Take an element and check to see if it exists in the new ArrayList
If it is present in the new ArrayList, do nothing. Else add it.
Do this until you have examined the last element of the ArrayList.
Then, the size of the new array list should be the number you are looking for.
You can use the lastIndexOf method and loop through the arraylist.
char count=0;
for(char i=0; i<araylist.size(); i++){
if(i == araylist.lastIndexOf(araylist.get(i))){
count++;
}
}
Tested.

INTERSECT result of 2 ArrayList containing Integer values

I've two ArrayList both containing Integer values. My objective is to get identical/common/duplicate values comparing these 2 list. In other words (in SQL parlance), I need the INTERSECT result of two lists, that is, values that appear in both list.
Example:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(300);
list2.add(600);
One kind of implementation/solution I could think along is looping one of the list something like:
ArrayList<Integer> intersectList = new ArrayList<Integer>();
for (Integer intValue : list1)
{
if(list2.contains(intValue))
intersectList.add(intValue);
}
In this case, intersectList would contain only 1 Integer item being added, that is 300, which appears in both list.
My question is, are there any better/fastest/efficient way of implementing this logic? Any options available in Apache Commons library?. Any other ideas/suggestions/comments are appreciated.
NOTE: For illustration purpose, I've just shown here 5 items and 2 items being added into the list. In my real-time implementation, there will be more than 1000 elements in each list. Therefore, performance is also a key factor to be considered.
If you're okay with overwriting result for list1:
list1.retainAll(list2);
otherwise clone/copy list1 first.
Not sure on performance though.
list1.retainAll(list2)//for intersection
Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.
ListUtils.intersection(list1, list2)

Categories