# | 功能表述 | JAVA | C# | 差异点 |
---|---|---|---|---|
1 | 新建List | List<String> list =Lists.newArrayList(); List<String> list =Lists.newLinkedList(); | List<string> list = new List<string>(); | 在C#中,List只有一种实现,即List java则有多种 |
2 | 新建Map | Map<String, Integer> map = Maps.newHashMap(); | Dictionary<string, int> dict = new Dictionary<string, int>(); | 在C#中,Map使用Dictionary<TKey, TValue>来实现, java则有多种 |
3 | 循环List | for (String s : list) { System.out.println(s); } | foreach (string s in list) { Console.WriteLine(s); } | |
4 | 循环Map | for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } | foreach (KeyValuePair<string, int> kvp in dict) { Console.WriteLine(kvp.Key + ": " + kvp.Value); } | |
5 | foreach | list.forEach(item -> System.out.println(item)); | list.ForEach(item => Console.WriteLine(item)); | |
6 | 以对象的某个属性为key,另一属性为value,转Map | Map<String, Integer> map = peopleList.stream() .collect(Collectors.toMap(Person::getName, Person::getAge)); | Dictionary<string, long> map = peopleList.ToDictionary(t => t.Name,t => t.Age); | java: key重复,后来者取而代之 c#: 报错 |
7 | 以对象的某个属性为key,自身为value,转Map | Map<String, Person> map = peopleList.stream() .collect(Collectors.toMap(Person::getName, Function.identity())); | Dictionary<string, Person> map= peopleList.ToDictionary(t => t.Name); | java: key重复,后来者取而代之 c#: 报错 |
8 | 给对象中某属性重新赋值 | peopleList.stream() .map(person -> { person.setAge(person.getAge() + 10); return person; }) .collect(Collectors.toList()); | peopleList= peopleList.Select( person => { x.age= x.age + 10; return person; }).ToList(); | |
9 | 对对象列表以某条件进行过滤 | List<Integer> result = list.stream() .filter(i -> i % 2 == 0) .collect(Collectors.toList()); | List<int> result = list.Where(i => i % 2 == 0).ToList(); | |
10 | 对对象列表进行分组并转为Map | Map<Integer, List<Person>> ageGroups = persons.stream() .collect(Collectors.groupingBy(Person::getAge)); | Dictionary<int, List<Person>> map ageGroups = persons.GroupBy(p => p.Age).ToDictionary(g => g.Key, g => g.ToList()); | |
11 | 对对象列表根据某属性进行排序 | List<Person> sortedPersons = persons.stream() .sorted(Comparator.comparing(Person::getAge)) .collect(Collectors.toList()); | List<Person>sortedPersons = persons.OrderBy(p => p.Age); | |
12 | 对对象列表根据某属性去重 | List<Person> distinctPersons = persons.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new)); | var distinctPersons = persons.GroupBy(p => p.Id).Select(g => g.First()).ToList(); |
C# 与 JAVA 常见代码对照表
于 2023-06-13 10:47:33 首次发布