In this part of code:
System.out.println("Alunos aprovados:");
String[] aprovados = {"d", "a", "c", "b"};
List<String> list = new ArrayList();
for (int i = 0; i < aprovados.length; i++) {
if (aprovados[i] != null) {
list.add(aprovados[i]);
}
}
aprovados = list.toArray(new String[list.size()]);
Arrays.sort(aprovados);
System.out.println(Arrays.asList(aprovados));
An example result of System.out.println is:
[a, b, c, d]
How could I modify the code above if I want a result like below?
a
b
c
d
Or, at least:
a,
b,
c,
d
Iterate through the elements, printing each one individually.
for (String element : list) {
System.out.println(element);
}
Alternatively, Java 8 syntax offers a nice shorthand to do the same thing with a method reference
list.forEach(System.out::println);
or a lambda
list.forEach(t -> System.out.println(t));
If one wants to display each element in the same line, without those brackets:
public static void main(String[] args) {
Set<String> stringSet = new LinkedHashSet<>();
stringSet.add("1");
stringSet.add("2");
stringSet.add("3");
stringSet.add("4");
stringSet.add("5");
int i = 0;
for (String value : stringSet) {
if (i < stringSet.size()-1) {
System.out.print(value + ",");
} else {
System.out.print(value);
}
i++;
}
}
Related
I currently have a String Array
String[] properSequence = ability.getSequence();
And I want to compare it to an ArrayList
ArrayList<String> sequence
As of right now I'm doing,
boolean matchesSequence = true;
String[] properSequence = ability.getSequence();
int index = 0;
for(String s : sequence) {
String s1 = properSequence[index];
if(!s1.equalsIgnoreCase(s)) {
matchesSequence = false;
break;
}
index++;
}
if(matchesSequence) {
// Matches, code
}
I was wondering if there's an easier/prettier way of doing this, seems a bit redundant.
Your code may throw ArrayIndexOutOfBoundsException. Check the bounds of array as well as the list as shown below:
for(int i = 0; i < Math.min(sequence.size(), properSequence.length); i++) {
if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
matchesSequence = false;
break;
}
}
Alternatively,
for(int i = 0; i < sequence.size() && i < properSequence.length; i++) {
if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
matchesSequence = false;
break;
}
}
You can use built-in equals method:
if(!Arrays.equals(sequence.toArray(),properSequence))
matchesSequence = false;
You could convert the String[] into an ArrayList and compare those two, but you can't do that if you want equalsIgnoreCase() in the comparison. However, if you put all the elements in the String[] and the ArrayList in upper (or lower) case, you could do this:
if (Arrays.asList(properSequence).equals(sequence))
{
...
}
Arrays and Lists are only considered equal to each other if the elements are equal and in the same order.
To compare an Array of object to a List of the same object you can do the following using the Arrays#compare method. Different versions have different capabilities. This example uses Strings and does a case insensitive compare. It also makes use of List.toArray introduced in JDK 11
List<String> list = List.of("A", "B", "C");
String[] array1 = { "a", "b", "c" };
String[] array2 = { "a", "c", "b" };
for (String[] array : new String[][] { array1, array2 }) {
if (Arrays.compare(array, list.toArray(String[]::new),
String.CASE_INSENSITIVE_ORDER) == 0) {
System.out.printf("%s equals %s%n",
Arrays.toString(array), list);
} else {
System.out.printf("%s does not equal %s%n",
Arrays.toString(array), list);
}
}
Prints
[a, b, c] equals [A, B, C]
[a, c, b] does not equal [A, B, C]
For the below code, I was hoping that elements of my arraylist would be modified but its not. How can I modify the elements
public class Main {
public static void main(String args[]){
ArrayList<String> aList = new ArrayList<>();
aList .add("aa");
aList .add("bb");
aList .add("cc");
new Main().modifyList(aList );
for(String s: aList ){
System.out.println(s);
}
}
public void modifyList(ArrayList<String> aList ){
for(String s: aList){
System.out.println(s);
s = s + "ss";
}
}
}
Its printing
aa
bb
cc
aa
bb
cc
Expected output
aa
bb
cc
aass
bbss
ccss
public void modifyList(ArrayList<String> aList ){
for(String s: aList){
System.out.println(s);
s = s + "ss";
}
}
Strings are immutable. So when you change s you are creating a new object that is different than the one in the ArrayList.
So you need to iterate over the array and replace the old value with the new using the set method.
for (int i = 0; i < alist.size(); i++) {
String s = aList.get(i) + "ss";
aList.set(i, s);
}
To simply append the changes do the following:
int len = alist.size();
for (int i = 0; i < len; i++) {
String s = aList.get(i) + "ss";
aList.add(s);
}
Prints
aa bb cc aass bbss ccss
Here is the problem, the variable s is unused and visible only in the scope of the for-loop:
for (String s: aList) {
System.out.println(s);
s = s + "ss"; // the variable 's' is unused
}
Either use List::set to replace the current value:
for (int i=0; i<aList.size(); i++) {
String s = aList.get(i);
System.out.println(s);
aList.set(i, s + "ss");
}
... or use the advantage of java-stream as of java-8 and map the list to a new one:
List<String> newList = aList.stream()
.map(s -> s + "ss")
.collect(Collectors.toList());
s = s + "ss" only updates the local variable s, it doesn't update the list.
If you want to update elements in a list, use a ListIterator and the set() method:
public static void modifyList(List<String> aList) {
for (ListIterator<String> iter = aList.listIterator(); iter.hasNext(); ) {
String s = iter.next();
s = s + "ss";
iter.set(s); // replace element in the list with new value
}
}
In Java 8+, you can use a lambda expression with the replaceAll() method:
public static void modifyList(List<String> aList) {
aList.replaceAll(s -> s + "ss");
}
Both will perform well even if the list doesn't handle random access well, e.g. if the list is a LinkedList.
Test
public static void main(String[] args) {
List<String> aList = new ArrayList<>(Arrays.asList("aa", "bb", "cc"));
modifyList(aList);
System.out.println(aList);
}
Output
[aass, bbss, ccss]
In order to solve this, you need to update each element as follows:
public void modifyList(ArrayList<String> aList){
for(int i = 0; i < aList.size(); i++){
String s = aList.get(i);
aList.set(i, s+"ss");
}
}
This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 5 years ago.
I have a list with values {"16","b","c","d","e","16","f","g","16","b"};
In this 16 and b are repeated so i want to delete all the entries of them and i need output as c, d, e, f, g. Below program works fine. Any better solutions?
public class Test {
public static void main(String[] args) {
ArrayList < String > l = new ArrayList < String > ();
String[] str = {
"16",
"b",
"c",
"d",
"e",
"16",
"f",
"g",
"16",
"b"
};
for (String s: str) {
l.add(s);
}
List ll = removeDups(l);
l.removeAll(ll);
System.out.println("Final List " + l);
}
private static List < String > removeDups(ArrayList < String > l) {
List < String > ll = new ArrayList < String > ();
for (String a: l) {
int x = Collections.frequency(l, a);
if (x > 1) {
ll.add(a);
}
}
return ll;
}
}
One way would be to use streams to find the frequency of each element:
Map<String, Long> counts = yourList.stream()
.collect(Collectors.groupingBy(
Function.identity(), // keep the element as the key
Collectors.counting())); // values will be the count
Then, you could use removeIf to remove elements based on a condition, for which you'll use the frequencies map calculated above:
yourList.removeIf(elem -> counts.get(elem) > 1);
System.out.println(yourList); // [c, d, e, f, g]
Another way would be to first find out which values have duplicates and which ones are unique. For this, we can use a Map<String, Boolean>:
Map<String, Boolean> duplicates = new LinkedHashMap<>();
yourList.forEach(elem -> duplicates.compute(elem, (k, v) -> v != null));
Here I'm iterating the list and, for each element, I'm putting it into the map, computing the value as true if the element is already present as a key, or false if it's unique.
Then, you could use removeIf on the list, with a predicate that simply returns the value from the map:
yourList.removeIf(duplicates::get);
System.out.println(yourList); // [c, d, e, f, g]
You can use Set to remove the duplicate elements from given array list.
Here is the sample code:
Set<String> myStrSet = new HashSet<String>();
Set<String> duplicateSet = new HashSet<String>();
for(String str : myArrayList){
if(myStrSet.contains(str)){
duplicateSet.add(str);
} else {
myStrSet.add(str);
}
}
for(String str : duplicateSet){
myStrSet.remove(str);
}
for(String str : myStrSet){
System.out.println("Print non-duplicate elements : " + str);
}
You can compare index and lastIndex for each element. If they are same, the element is unique. We can filter those elements.
// imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// sample code
String[] str = {"16","b","c","d","e","16","f","g","16","b"};
List<String> list = Arrays.asList(str); // List from the array
List<String> newList = new ArrayList<String>();
for(String myStr : list){
if(list.indexOf(myStr) == list.lastIndexOf(myStr)){
/*
* This is a unique element as its index and lastIndex in list are same.
* Add it to new list.
*/
newList.add(myStr);
}
}
// Freeing resources
str = null;
list = null;
System.out.println("Final List: "+ newList);
I think this will do
public class DeleteDuplicates {
public static void main(String[] args) {
String[] str={"16","b","c","d","e","16","f","g","16","b"};
List<String> l= new ArrayList<String>();
Set<String> set = new HashSet<String>();
for(String string : str) {
if(set.add(string))
l.add(string);
else
l.remove(string);
}
System.out.println(l);
}
}
I've been asked to write a program to find the permutations of a String and its Sub-Strings using an ArrayList. I came up with a solution, but it is not displaying the required output. So, I would appreciate if someone could enlighten me a bit on this.
The question is as follows:
To compute all permutations of a string and it's sub-strings. For example, given a string S such as "abc", it should output a list/array of strings retlist [a, b, c, ab, ba, ac, ca, bc, cb, abc, acb, bac, bca, cab, cba]. Your code should take S as input, and produce retlist for the permuted list. On top of having a code that works, please optimize the code for efficiency of speed and memory (we will be testing for large strings and the faster it goes, the better).
As said in the question, when permutating a string of "abc", it should print a result as below:
[a, b, c, ab, ba, ac, ca, bc, cb, abc, acb, bac, bca, cab, cba]
What I came up with so far:
import java.util.ArrayList;
import java.util.List;
public class Permutation {
public static void main(String[] args) {
enumerateSubString("abc");
}
public static List<String> enumerateSubString(String S_input) {
ArrayList<String> retlist = new ArrayList<String>();
int n = S_input.length();
if (n == 1) {
retlist.add(S_input);
} else {
for (int i = 0; i < n; i++) {
retlist.addAll(enumerateSubString(S_input.substring(0, i) + S_input.substring(i + 1, n)));
}
}
System.out.print(retlist);
return retlist;
}
}
And the result that I am getting right now with the above code:
[c][b][c, b][c][a][c, a][b][a][b, a][c, b, c, a, b, a]
Thanks
Adding another answer with generic algorithm. This will give all permutations in the order mentioned. Hope this solve purpose
public class Test {
public static void main(String[] args) {
String s = "abc";
Map<Integer, List<String>> map = new HashMap<>();
List<String> strArray = new ArrayList<String>(Arrays.asList(s.split("")));
map.put(1, strArray);
if (strArray.size() > 1) {
new Test().enumerateSubString(strArray.size(), map);
}
System.out.println(map.values());
}
public void enumerateSubString(int n, Map<Integer, List<String>> map) {
if (!map.containsKey(n)) {
map.put(n, new ArrayList<>());
}
if (n == 2) {
// List of string with each having 1 character
List<String> list_1 = map.get(1);
// List of string which each having 2 characters
List<String> list_2 = new ArrayList<>();
for (int i = 0; i < list_1.size(); i++) {
for (int j = i + 1; j < list_1.size(); j++) {
list_2.add(list_1.get(i) + list_1.get(j));
list_2.add(swap(list_1.get(i) + list_1.get(j)));
}
}
// Map list_2 to key 2
map.put(n, list_2);
} else {
// Recursive function
enumerateSubString(n - 1, map);
// List of string with each having n-1 characters
List<String> list = map.get(n - 1);
// List of string with each having n characters
List<String> list_n = map.get(n);
// Add each character to list of n-1 to get n charater string list
for (String l1 : map.get(1)) {
for (String l : list) {
// this condition is to avoid repetation of charaters n
// String
if (l.indexOf(l1) < 0) {
list_n.add(l1 + l);
}
}
}
}
}
// Function to swap characters
private String swap(String str) {
String s1 = str.substring(1) + str.substring(0, 1);
return s1;
}}
I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose