Answer the question
In order to leave comments, you need to log in
How to implement the correct class structure for adding data to a collection in Java?
Hello.
I have a task already solved in JavaScript:
const a = ['колба', 'кот', 'бокал', 'ток', 'тест', 'отк', 'тор', 'рот'];
function getAnagrams(s) {
const m = new Map();
for (let i of s) {
// console.log(i);
let w = i.split('').sort().join('');
console.log(w);
if (m.has(w)) {
m.get(w).push(i);
} else {
m.set(w, []); // key => value
m.get(w).push(i);
}
}
console.log(m);
/*
Map {
'абкло' => [ 'колба', 'бокал' ],
'кот' => [ 'кот', 'ток', 'отк' ],
'естт' => [ 'тест' ],
'орт' => [ 'тор', 'рот' ] }
*/
console.log('----------------------------------------');
return Array.from(m.values()).filter(i => i.length > 1);
}
console.log(getAnagrams(a));
/*
[ [ 'колба', 'бокал' ],
[ 'кот', 'ток', 'отк' ],
[ 'тор', 'рот' ] ]
*/
// console.log(getAnagrams(['нос', 'сон', 'снедь', 'днесь']));
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("нос");
list.add("сон");
list.add("снедь");
list.add("днесь");
// System.out.println(list);
Anagrams anagrams = new Anagrams(list);
System.out.println(anagrams.getAnagrams());
}
}
class Words {
public List<Word> words = new ArrayList<>();
public Words(Word word) {
this.words.add(word);
}
}
class Word {
private String word;
public void setWord(String word) {
this.word = word;
}
}
class Anagrams {
public List<String> words;
public Anagrams(List<String> words) {
this.words = words;
}
public boolean getAnagrams() {
System.out.println(words);
Map<String, String> map = new HashMap<>();
for (int i = 0; i < words.size(); i++) {
// System.out.println(words.get(i));
String currentValue = words.get(i);
String word = Stream.of(currentValue.split(""))
.sorted()
.collect(Collectors.joining());
System.out.println(word);
if (map.containsKey(word)) {
} else {
// map.put(word, );
}
System.out.println(map);
}
return true;
}
}
Answer the question
In order to leave comments, you need to log in
The Word and Words classes are not needed.
Use Set instead of Map.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question